How do I convert a byte array to Base64 in Java?
Use java.util.Base64
to encode a byte array:
This gets you the Base64 String directly from yourByteArray
.
Applications of Base64 encoding
Base64 is a technique of encoding binary data into ASCII strings. Common use-cases involve:
- Creating data URIs for embedding images in HTML or CSS
- Encoding binary data for inclusion in JSON or XML, frequently used in APIs
- Storing binary data in text-centric formats such as cookies
Solutions for older Java versions & third-party libraries
Working on an older project or prefer third-party libraries for Base64 encoding/decoding? We've got a few alternatives:
- Apache Commons Codec: Leverage
Base64.encodeBase64(byte[])
andBase64.decodeBase64(String)
for encoding and decoding. - Spring Framework's utility class: Utilize
Base64Utils.encodeToString(byte[])
andBase64Utils.decodeFromString(String)
in Spring-based applications.
Base64 encoding in Android development
Android incorporates its own Base64
utility class within android.util.Base64
, tailored for Android-specific environments:
- Convert a byte array to a Base64 string with
Base64.encodeToString(bytes, Base64.DEFAULT)
. - Decode Base64 to byte array using
Base64.decode(String, Base64.DEFAULT)
.
Ensure API Level is 8 or higher when using Android's Base64 utility.
Avoid common mistakes - Encoding best practices
Watch out for common missteps and adopt effective practices when encoding and decoding Base64:
- Avoid: Using inappropriate methods that may corrupt your data or degrade performance.
- Ensure: Appropriately handling padding characters (
=
) during encoding and decoding processes. - Validate: Always verify input to Base64 encoding is a clean, well-formed byte array to avert runtime exceptions.
Encode byte array with Java 8's Base64
Java 8 introduced an efficient java.util.Base64
class for simpler encoding and decoding:
- Convert byte array to Base64:
String encoded = Base64.getEncoder().encodeToString(someByteArray); //Easy-peasy, lemon-squeezy! 🍋
- Decode from Base64 to byte array:
byte[] decoded = Base64.getDecoder().decode(someBase64String); // Back you go, boomerang! 🔄
The utility class from Java 8 onwards handles MIME, URL, and padding concerns without external dependencies.
Choose the right encoder for your project
The choice of Base64 encoder impacts performance and ease of code management. Consider:
- If using Java 8 or later, make use of Java's Built-in Base64.
- Leverage Spring Framework or Apache Commons Codec if they're already part of your project.
- For Android Development, stick with
android.util.Base64
for optimal compatibility.
Was this article helpful?