Base64 Java encode and decode a string
Here's how to encode a string to Base64 using Base64.getEncoder().encodeToString(str.getBytes())
:
Next, decode with new String(Base64.getDecoder().decode(encoded))
:
Quick and easy with java.util.Base64 - no sweat!
Choosing the right tools
Ensure you're using the right implementation:
- Java 8+: Stick with
java.util.Base64
. Trust me, it's powerful! - Pre-Java 8: Go with
javax.xml.bind.DatatypeConverter
ororg.apache.commons.codec.binary.Base64
. Old but gold!
Working on an Android app? Switch to android.util.Base64
. If it's a Spring application, try Spring Security's Base64
class for a seamless integration.
Understanding Base64
Base64 encoding morphs binary data into text format for safe and sound transmission over text-only media. This is due to its process of dividing input into 6-bit chunks and transforming each into a character from a set of 64 - hence, "Base64".
Special considerations
- Padding: Discard padding? Use
.withoutPadding()
. - Charset: When converting byte arrays, use
Charset.forName("UTF-8")
to avoid those pesky character encoding issues.
Error handling
Catch unexpected exceptions like a pro. Wrap your operations in try-catch
blocks:
Best practices for maintainability
- Maintain readability: Code that's easy to read is easy to maintain. Write pretty!
- Consistency verification: Don't trust, verify. Compare your original, encoded, and decoded values.
- Byte conversion: Ensure to convert strings to bytes before encoding. Get it right!
Additional functions and features
- Stream encoding/decoding: Check out
java.util.Base64.Encoder
andDecoder
stream functionality for handling large volumes of data. - URL safe encoding: Use
Base64.getUrlEncoder()
for URL specific encoding. - Advanced handling: With
org.apache.commons.codec.binary.Base64
, it's more than just vanilla Base64!
Was this article helpful?