Base64 Encoding in Java: java.util.Base64, Apache Commons, and More

Published on February 8, 2026 · 7 min read

Java has excellent built-in support for Base64 encoding and decoding since Java 8. Whether you're working with strings, files, images, or network protocols, the java.util.Base64 class has you covered. This guide covers everything from basic usage to advanced patterns.

The Modern Way: java.util.Base64 (Java 8+)

Since Java 8, the standard library includes the java.util.Base64 class with three variants:

  • Basic: Standard Base64 as defined in RFC 4648. Uses + and / characters.
  • URL-safe: Uses - and _ instead, and omits padding. Safe for URLs and filenames.
  • MIME: Produces lines of 76 characters with CRLF line endings. Used for email attachments.

Encoding and Decoding Strings

import java.util.Base64;

// Basic encoding
String original = "Hello, Java!";
String encoded = Base64.getEncoder()
    .encodeToString(original.getBytes("UTF-8"));
System.out.println(encoded); // "SGVsbG8sIEphdmEh"

// Basic decoding
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes, "UTF-8");
System.out.println(decoded); // "Hello, Java!"

// URL-safe encoding
String urlSafe = Base64.getUrlEncoder()
    .encodeToString(original.getBytes("UTF-8"));
System.out.println(urlSafe); // "SGVsbG8sIEphdmEh" (no padding)

// MIME encoding (for email)
String mimeEncoded = Base64.getMimeEncoder()
    .encodeToString(original.getBytes("UTF-8"));

Encoding Files and Images

To encode a file to Base64, read it as bytes and encode. This is commonly used for embedding images in HTML or sending files via APIs:

import java.nio.file.*;
import java.util.Base64;

// Encode a file to Base64
Path path = Paths.get("photo.jpg");
byte[] fileBytes = Files.readAllBytes(path);
String base64 = Base64.getEncoder().encodeToString(fileBytes);

// Create a data URI for embedding in HTML
String mimeType = "image/jpeg";
String dataUri = "data:" + mimeType + ";base64," + base64;

// Decode Base64 back to a file
byte[] decodedBytes = Base64.getDecoder().decode(base64);
Files.write(Paths.get("decoded-photo.jpg"), decodedBytes);

⚠️ Memory Warning

Reading entire files into memory with Files.readAllBytes() can cause OutOfMemoryError for large files. For files over ~100MB, use streaming with Base64.getInputStream() and Base64.getOutputStream().

Streaming Large Files

For large files, use the streaming API to avoid loading everything into memory:

import java.util.Base64;
import java.io.*;

// Encode a large file using streaming
try (InputStream is = new FileInputStream("large-file.bin");
     OutputStream os = Base64.getEncoder().encode(
         new FileOutputStream("large-file.b64"))) {
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
}

// Decode a large Base64 file using streaming
try (InputStream is = Base64.getDecoder().wrap(
         new FileInputStream("large-file.b64"));
     OutputStream os = new FileOutputStream("large-file-decoded.bin")) {
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
}

Using Apache Commons Codec

If you're on an older Java version (pre-8) or prefer a library with additional features, Apache Commons Codec is widely used:

// Add dependency: commons-codec:commons-codec:1.16.0
import org.apache.commons.codec.binary.Base64;

// Encode
String encoded = new String(
    Base64.encodeBase64("Hello, Commons!".getBytes("UTF-8")));

// Decode
String decoded = new String(
    Base64.decodeBase64(encoded), "UTF-8");

// URL-safe
String urlSafe = new String(
    Base64.encodeBase64URLSafe("Hello!".getBytes("UTF-8")));

// Encode with line breaks (MIME style)
String mime = new String(
    Base64.encodeBase64Chunked("Hello!".getBytes("UTF-8")));

Base64 in Spring Framework

Spring provides its own Base64 utilities that wrap the Java 8 API with additional convenience methods:

import org.springframework.util.Base64Utils;

// Encode
byte[] encoded = Base64Utils.encode("Hello, Spring!".getBytes("UTF-8"));

// Decode
byte[] decoded = Base64Utils.decode(encoded);

// Encode to string
String encodedString = Base64Utils.encodeToString(
    "Hello, Spring!".getBytes("UTF-8"));

// Decode from string
byte[] decodedFromString = Base64Utils.decodeFromString(encodedString);

// URL-safe variants
String urlSafe = Base64Utils.encodeToUrlSafeString(
    "Hello!".getBytes("UTF-8"));
byte[] urlDecoded = Base64Utils.decodeFromUrlSafeString(urlSafe);

Handling Images in Android

On Android, you can use the same android.util.Base64 class (not to be confused with java.util.Base64):

import android.util.Base64;
import android.graphics.Bitmap;
import java.io.ByteArrayOutputStream;

// Convert Bitmap to Base64
Bitmap bitmap = ...; // your bitmap
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String base64 = Base64.encodeToString(
    imageBytes, Base64.DEFAULT);

// Convert Base64 back to Bitmap
byte[] decodedBytes = Base64.decode(base64, Base64.DEFAULT);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(
    decodedBytes, 0, decodedBytes.length);

Performance Tips

  • Use the streaming API for files larger than 10MB to avoid memory issues.
  • Reuse encoder/decoder instances — they are thread-safe in Java 8+.
  • Specify charset explicitly with getBytes("UTF-8") instead of relying on the default charset.
  • Use try-with-resources when working with streams to ensure proper cleanup.
  • Consider compression before Base64 encoding for large text data — Base64 adds 33% overhead, so compress first, then encode.

Common Pitfalls

  • Missing charset: Always specify UTF-8 when converting between strings and bytes. Platform-dependent defaults can cause issues.
  • Memory with large files: Don't use readAllBytes() for files over ~100MB.
  • URL vs Basic confusion: Use the right encoder variant. Basic Base64 in a URL will cause issues with + and / characters.
  • Android vs Java: Android has its own android.util.Base64with different flags. Don't mix them up.

Conclusion

Java provides robust Base64 support through the standard library, Apache Commons, and Spring. The java.util.Base64 class introduced in Java 8 covers most use cases, while Apache Commons is useful for older Java versions or when you need additional features like chunked encoding.

Try our Base64 Encoder & Decoder to quickly test your Base64 strings, or use the URL-Safe Encoder for JWT tokens and URL parameters.