In Java, Base64 encoding and decoding are commonly used for encoding binary data as text.
This is especially useful in contexts where data needs to be safely transmitted over networks, stored in text files, or embedded in XML or JSON.
Java provides built-in support for Base64 encoding and decoding through the java.util.Base64 class introduced in Java 8.
Table of Contents
Base64 Encoding and Decoding Basics
The Base64 class provides three built-in encoders and decoders:
- Basic: Standard Base64 encoding without any line separators.
- URL and Filename Safe: Base64 encoding modified to be URL and filename safe by replacing certain characters.
- MIME: Base64 encoding suitable for MIME (Multipurpose Internet Mail Extensions) with line breaks.
1. Basic Base64 Encoding and Decoding
The Base64.getEncoder() and Base64.getDecoder() methods provide basic encoding and decoding.
Example: Encoding and Decoding a Simple String
import java.util.Base64; public class Base64BasicExample { public static void main(String[] args) { String originalString = "Hello, World!"; // Encode String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes()); System.out.println("Encoded String: " + encodedString); // Decode byte[] decodedBytes = Base64.getDecoder().decode(encodedString); String decodedString = new String(decodedBytes); System.out.println("Decoded String: " + decodedString); } }
Explanation
- Encoding: Base64.getEncoder().encodeToString(originalString.getBytes()) encodes the originalString to Base64.
- Decoding: Base64.getDecoder().decode(encodedString) decodes the Base64 string back to bytes, which are then converted to a string.
Output
Encoded String: SGVsbG8sIFdvcmxkIQ== Decoded String: Hello, World!
2. Encoding and Decoding with URL and Filename Safe Base64
The URL-safe encoder replaces the + and / characters with – and _, making the encoded string safe for URLs and filenames.
Example: URL-Safe Encoding and Decoding
import java.util.Base64; public class Base64UrlExample { public static void main(String[] args) { String originalString = "Hello, URL-safe World!"; // Encode using URL-safe Base64 encoder String encodedUrlString = Base64.getUrlEncoder().encodeToString(originalString.getBytes()); System.out.println("URL-Safe Encoded String: " + encodedUrlString); // Decode byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrlString); String decodedString = new String(decodedBytes); System.out.println("Decoded String: " + decodedString); } }
Explanation
- URL Encoding: Base64.getUrlEncoder().encodeToString() encodes the string using a URL-safe Base64 variant.
- URL Decoding: Base64.getUrlDecoder().decode() decodes the URL-safe Base64 string back to the original text.
Output
URL-Safe Encoded String: SGVsbG8sIFVSTC1zYWZlIFdvcmxkIQ== Decoded String: Hello, URL-safe World!
3. MIME Base64 Encoding with Line Breaks
The MIME encoder inserts line breaks every 76 characters, which is suitable for encoding large data like files or images in MIME format for emails.
Example: MIME Encoding and Decoding
import java.util.Base64; public class Base64MimeExample { public static void main(String[] args) { String originalString = "This is a long string that might need to be split into multiple lines for MIME encoding purposes."; // Encode with MIME Base64 encoder String encodedMimeString = Base64.getMimeEncoder().encodeToString(originalString.getBytes()); System.out.println("MIME Encoded String: " + encodedMimeString); // Decode byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMimeString); String decodedString = new String(decodedBytes); System.out.println("Decoded String: " + decodedString); } }
Explanation
- MIME Encoding: Base64.getMimeEncoder().encodeToString() encodes the string and adds line breaks every 76 characters.
- MIME Decoding: Base64.getMimeDecoder().decode() decodes the MIME Base64-encoded string back to the original text.
Output
MIME Encoded String: VGhpcyBpcyBhIGxvbmcgc3RyaW5nIHRoYXQgbWlnaHQgbmVlZCB0byBiZSBzcGxpdCBp bnRvIG11bHRpcGxlIGxpbmVzIGZvciBNSU1FIGVuY29kaW5nIHB1cnBvc2VzLg== Decoded String: This is a long string that might need to be split into multiple lines for MIME encoding purposes.
4. Encoding and Decoding Binary Data (e.g., Image Files)
Base64 encoding is often used to encode binary data for transmission or storage. This example demonstrates encoding an image file into a Base64 string and decoding it back to the original format.
Example: Encoding and Decoding an Image File
import java.util.Base64; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class Base64BinaryExample { public static void main(String[] args) { try { // Load the image file as bytes byte[] fileContent = Files.readAllBytes(Paths.get("example.png")); // Encode the bytes into a Base64 string String encodedString = Base64.getEncoder().encodeToString(fileContent); System.out.println("Encoded Image String: " + encodedString); // Decode the Base64 string back to bytes byte[] decodedBytes = Base64.getDecoder().decode(encodedString); // Write the decoded bytes to a new file Files.write(Paths.get("decoded_example.png"), decodedBytes); System.out.println("Image successfully decoded and saved as 'decoded_example.png'"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }
Explanation
- Encoding: Files.readAllBytes(Paths.get(“example.png”)) reads the binary content of an image file. We then encode it using Base64.getEncoder().encodeToString().
- Decoding: Base64.getDecoder().decode(encodedString) converts the Base64 string back into bytes, which are saved as a new image file.
5. Customizing MIME Encoding with Line Length and Line Separator
The Base64.getMimeEncoder() allows you to specify a custom line length and line separator. This can be useful when working with protocols or systems that require specific formatting.
Example: Custom MIME Encoding with Line Length and Separator
import java.util.Base64; public class Base64CustomMimeExample { public static void main(String[] args) { String originalString = "This is a custom MIME encoding example that requires specific line lengths and separators."; // Customize line length to 50 characters and use "#" as the line separator Base64.Encoder mimeEncoder = Base64.getMimeEncoder(50, "#".getBytes()); // Encode the string String encodedString = mimeEncoder.encodeToString(originalString.getBytes()); System.out.println("Custom MIME Encoded String:\n" + encodedString); } }
Explanation
- Custom MIME Encoding: Base64.getMimeEncoder(50, “#”.getBytes()) encodes the string with a custom line length of 50 characters and uses # as the line separator.
- The output is formatted with line breaks and custom separators.
6. Encoding and Decoding Objects Using Serialization
Base64 can be used to encode objects by serializing them into a byte array, then encoding the byte array to a Base64 string.
Example: Serializing and Encoding an Object to Base64
import java.util.Base64; import java.io.*; class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class Base64ObjectExample { public static void main(String[] args) { Person person = new Person("Alice", 30); try { // Serialize and encode the object to Base64 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(person); objectOutputStream.close(); String encodedObject = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()); System.out.println("Encoded Object: " + encodedObject); // Decode and deserialize the object from Base64 byte[] decodedBytes = Base64.getDecoder().decode(encodedObject); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decodedBytes); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); Person decodedPerson = (Person) objectInputStream.readObject(); objectInputStream.close(); System.out.println("Decoded Object: " + decodedPerson); } catch (IOException | ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } }
Explanation
- Serialization: We serialize the Person object to a byte array and then encode it to a Base64 string.
- Deserialization: We decode the Base64 string back to bytes and then deserialize it to a Person object.
Summary
Java’s Base64 class provides a robust way to handle Base64 encoding and decoding.
Key points include:
- Basic Encoding: Used for general-purpose encoding, with no line breaks.
- URL and Filename Safe Encoding: Uses URL-safe characters, making the output suitable for URLs and filenames.
- MIME Encoding: Adds line breaks, making it suitable for large data and MIME-based applications.
- Binary Data: Useful for encoding binary files like images or documents.
- Object Serialization: Enables encoding of objects by serializing them to a byte array.
By mastering these methods, you can securely and efficiently handle data transmission and storage requirements in Java applications.