Base64 in Java

Last updated: February 2026

How to encode and decode Base64 in Java using the java.util.Base64 class

How Do You Encode a String to Base64 in Java?

Use java.util.Base64.getEncoder() to obtain a Base64.Encoder instance. This class has been available since Java 8. Call encodeToString() to produce a String output, or call encode() to receive a byte[] array. The encoder uses the standard Base64 alphabet defined in RFC 4648 Section 4.

import java.util.Base64;

String original = "Hello, World!";
String encoded = Base64.getEncoder().encodeToString(original.getBytes("UTF-8"));
System.out.println(encoded); // SGVsbG8sIFdvcmxkIQ==

The getBytes("UTF-8") call converts the string to a UTF-8 byte array before encoding. Always specify the character encoding explicitly to avoid platform-dependent behavior. The encoder instance returned by getEncoder() is thread-safe and reusable. For a browser-based alternative, use the Base64 text encoder.

How Do You Decode Base64 in Java?

Use Base64.getDecoder().decode() to convert a Base64 string back to its original bytes. The decode() method accepts either a String or a byte[] and returns a byte[]. Construct a new String from the byte array with the correct character encoding.

import java.util.Base64;

byte[] decoded = Base64.getDecoder().decode("SGVsbG8sIFdvcmxkIQ==");
String result = new String(decoded, "UTF-8");
System.out.println(result); // Hello, World!

The decoder throws IllegalArgumentException if the input contains characters outside the Base64 alphabet. Validate input strings before decoding in production code. To decode Base64 directly in your browser, use the Base64 text decoder.

What Base64 Encoder Types Does Java Provide?

Java provides 3 encoder/decoder pairs through static factory methods on the Base64 class. Each pair implements a different Base64 variant defined in RFC 4648 or RFC 2045. The basic encoder handles general-purpose encoding, the URL encoder produces URL-safe output, and the MIME encoder formats output for email transport.

MethodEncoder TypeLine LengthPaddingUse Case
getEncoder()Basic (RFC 4648 §4)No line breaksYesGeneral purpose
getUrlEncoder()URL-safe (RFC 4648 §5)No line breaksYesURLs, JWT tokens
getMimeEncoder()MIME (RFC 2045)76 chars + CRLFYesEmail attachments

Each encoder has a corresponding decoder: getDecoder(), getUrlDecoder(), and getMimeDecoder(). The MIME decoder is lenient and ignores characters outside the Base64 alphabet, including line breaks. The basic and URL decoders reject non-Base64 characters with an exception. For a deeper understanding of these encoding variants, see the What is Base64 guide.

How Do You Use URL-Safe Base64 in Java?

Use Base64.getUrlEncoder() to produce URL-safe Base64 output. This encoder replaces + with - and / with _ as defined in RFC 4648 Section 5. For JWT tokens and URL parameters, chain withoutPadding() to omit trailing = characters.

import java.util.Base64;

byte[] data = "subjects?abcd".getBytes("UTF-8");

// URL-safe with padding
String withPad = Base64.getUrlEncoder().encodeToString(data);
System.out.println(withPad); // c3ViamVjdHM_YWJjZA==

// URL-safe without padding (common for JWT)
String noPad = Base64.getUrlEncoder().withoutPadding().encodeToString(data);
System.out.println(noPad); // c3ViamVjdHM_YWJjZA

The URL-safe encoder prevents conflicts when Base64 strings appear in query parameters, fragment identifiers, or file names. Decode URL-safe strings with Base64.getUrlDecoder().decode(). The URL-safe Base64 tool provides browser-based encoding with the same alphabet.

How Do You Encode a File to Base64 in Java?

Read the file into a byte array using Files.readAllBytes(), then pass the bytes to Base64.getEncoder().encodeToString(). This approach loads the entire file into memory, so it works for files that fit within the JVM heap.

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

byte[] fileBytes = Files.readAllBytes(Path.of("image.png"));
String encoded = Base64.getEncoder().encodeToString(fileBytes);

// Create a data URI for HTML embedding
String dataUri = "data:image/png;base64," + encoded;
System.out.println(dataUri);

For images, prepend the appropriate MIME type to create a data URI string. The Base64 file encoder performs the same operation in your browser without uploading the file to a server. To decode a Base64 file back to binary, reverse the process with Files.write() and Base64.getDecoder().decode().

How Do You Use Base64 with Streams in Java?

Base64.getEncoder().wrap(OutputStream) returns a Base64-encoding output stream, and Base64.getDecoder().wrap(InputStream) returns a Base64-decoding input stream. These wrappers process data incrementally, avoiding the need to load entire files into memory. Use streams for large files that exceed available heap space.

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

// Encode a file using streams (low memory usage)
try (OutputStream out = Base64.getEncoder().wrap(
        new FileOutputStream("image.b64"))) {
    Files.copy(Path.of("image.png"), out);
}

// Decode a Base64 file using streams
try (InputStream in = Base64.getDecoder().wrap(
        new FileInputStream("image.b64"))) {
    Files.copy(in, Path.of("decoded.png"));
}

The stream wrappers buffer data internally and process it in chunks. This approach handles files of any size because only a small buffer resides in memory at any time. The wrap() method is available on basic, URL-safe, and MIME encoders and decoders. Use the Base64 size calculator to estimate encoded output size before processing.

What Java Base64 Methods Are Available?

The java.util.Base64 class contains 6 static factory methods and 2 inner classes (Encoder and Decoder). The Encoder class provides 3 encoding methods plus a padding modifier and a stream wrapper. The Decoder class provides 2 decoding methods and a stream wrapper.

Base64 Static Factory Methods

MethodReturnsDescription
getEncoder()Base64.EncoderBasic encoder (RFC 4648 §4)
getDecoder()Base64.DecoderBasic decoder
getUrlEncoder()Base64.EncoderURL-safe encoder (RFC 4648 §5)
getUrlDecoder()Base64.DecoderURL-safe decoder
getMimeEncoder()Base64.EncoderMIME encoder (RFC 2045, 76-char lines)
getMimeDecoder()Base64.DecoderMIME decoder (ignores non-Base64 chars)

Encoder Instance Methods

MethodReturnsDescription
encode(byte[])byte[]Encode to byte array
encodeToString(byte[])StringEncode to String
encode(byte[], byte[])intEncode into provided buffer, returns length
wrap(OutputStream)OutputStreamWrap stream for encoding on write
withoutPadding()Base64.EncoderReturn encoder that omits = padding

Decoder Instance Methods

MethodReturnsDescription
decode(String)byte[]Decode String to byte array
decode(byte[])byte[]Decode byte array to byte array
decode(byte[], byte[])intDecode into provided buffer, returns length
wrap(InputStream)InputStreamWrap stream for decoding on read

All Encoder and Decoder instances are immutable and thread-safe. Store them as static final fields for reuse across your application. For a complete reference on the Base64 alphabet used by these methods, see the Base64 character table.

Frequently Asked Questions

Which Java version added Base64 support?

Java 8 (released March 2014) added the java.util.Base64 class. This class provides static factory methods getEncoder(), getDecoder(), getUrlEncoder(), getUrlDecoder(), getMimeEncoder(), and getMimeDecoder() for all standard Base64 encoding variants defined in RFC 4648 and RFC 2045.

Is Apache Commons Codec still needed for Base64 in Java?

No. Since Java 8, the java.util.Base64 class provides built-in Base64 encoding and decoding. The Apache Commons Codec library (org.apache.commons.codec.binary.Base64) is no longer required for Base64 operations. The standard library implementation covers basic, URL-safe, and MIME encoding variants. Remove the dependency to reduce your application's footprint.

How do you encode Base64 without padding in Java?

Call the withoutPadding() method on any Encoder instance. For example: Base64.getEncoder().withoutPadding().encodeToString(data). This returns a Base64 string without trailing = characters. The withoutPadding() method works with basic, URL-safe, and MIME encoders. The decoder handles both padded and unpadded input automatically.

Is java.util.Base64 thread-safe?

Yes. Both Base64.Encoder and Base64.Decoder instances returned by the static factory methods are thread-safe and stateless. A single instance can be shared across multiple threads without synchronization. Store encoder and decoder instances as static final fields for reuse throughout your application.

What is the difference between getEncoder and getMimeEncoder?

getEncoder() returns a basic encoder that produces a single continuous Base64 string with no line breaks, following RFC 4648 Section 4. getMimeEncoder() returns an encoder that inserts CRLF (\r\n) line separators every 76 characters, following RFC 2045. Use the MIME encoder for email attachments and multipart messages. Use the basic encoder for data URIs, JSON payloads, and API responses.

Related Base64 Tools and Guides