Home >Java >javaTutorial >How to Encode Data to Base64 in Java?
Encoding Data as Base64 in Java
Encoding Using Apache Commons
In Java 7, the sun.misc.BASE64Encoder class previously used for Base64 encoding is now deprecated. To encode using Apache Commons, replace your imports with:
import org.apache.commons.codec.binary.Base64;
And use the Base64 class as shown below:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
Encoding Using java.util.Base64 in Java 8
Java 8 introduced the java.util.Base64 package for Base64 encoding. Import it with:
import java.util.Base64;
Then utilize the Base64 encoder and decoder static methods:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes()); byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
Direct Encoding from String to String
To encode a string and obtain the encoded string directly:
String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
Considerations Regarding sun.misc Packages
It is recommended to avoid using classes from sun.misc packages as they may have been removed or their behavior modified in future Java versions.
The above is the detailed content of How to Encode Data to Base64 in Java?. For more information, please follow other related articles on the PHP Chinese website!