Encoding as Base64 in Java
Quickly convert text into Base64 in Java using the Base64
class:
And here's how you can decode:
Just replace "text"
with your data and you're good to encode and decode!
Explicit character encoding
Specify your character encoding to avoid strange output. Let's secure with UTF-8:
This ensures consistency while dealing with different environments.
Encoding bytes, not just words!
You can also encode byte arrays directly:
The encode()
method is also available if you want the encoded data as a byte array instead of a string.
Avoiding the "sunburn"
The sun.*
packages seem tempting but are unstable. Stick to java.util.Base64
. For those running nostalgia on Java 7 or lower, use javax.xml.bind.DatatypeConverter
.
Exploring other libraries
java.util.Base64
got you covered. But Google Guava's BaseEncoding
is another player in town:
Remember to add the Guava dependency in your pom.xml
if you decide to go down this road.
Decoding: The Art and the Exceptions
Use the correct decode()
variant for your input type and handle exceptions like a pro:
Java version compatibility
Pick the right tool for your Java version:
- Java 8 or later: Use
java.util.Base64
. - Pre-Java 8: Alternatives like Guava or
javax.xml.bind.DatatypeConverter
are your friends.
Troubleshooting your Base64 woes
Facing unexpected behavior? Try these:
- Check all IDE configurations.
- Ensure input data is in the correct format.
- Test output against expected results.
Was this article helpful?