Base64 Encode & Decode in Java

Encode or decode below — it runs locally in your browser — then grab the canonical Java code. Since Java 8, the standard library ships java.util.Base64 with no external dependency: getEncoder() for standard, getUrlEncoder() for URL-safe, and getMimeEncoder() for email.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

The key pattern is String → getBytes() → getEncoder() → encodeToString(), and the reverse with getDecoder():

import java.util.Base64;
import java.nio.charset.StandardCharsets;

// Encode
String encoded = Base64.getEncoder()
    .encodeToString("Hello, world!".getBytes(StandardCharsets.UTF_8));
System.out.println(encoded); // SGVsbG8sIHdvcmxkIQ==

// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println(decoded); // Hello, world!

Tip: java.util.Base64 is Java 8+ — no library needed. Always specify StandardCharsets.UTF_8 when converting between String and byte[]; never rely on the default platform charset.

URL-safe Base64

For JWTs, URLs, and filenames, use the URL-safe alphabet (- and _ instead of + and /):

// URL-safe encode, padding stripped (JWT-style)
String urlSafe = Base64.getUrlEncoder()
    .withoutPadding()
    .encodeToString("Hello, world!".getBytes(StandardCharsets.UTF_8));
System.out.println(urlSafe); // SGVsbG8sIHdvcmxkIQ

// URL-safe decode (handles padded and unpadded input)
byte[] decoded = Base64.getUrlDecoder().decode(urlSafe);

MIME / files

The MIME encoder splits output into 76-character lines (for email), and you can encode any byte[] read from a file:

import java.nio.file.Files;
import java.nio.file.Paths;

// MIME encoding with line breaks (76 chars per line)
String mime = Base64.getMimeEncoder().encodeToString(largeData);

// Encode a file to Base64
byte[] fileBytes = Files.readAllBytes(Paths.get("image.png"));
String encoded = Base64.getEncoder().encodeToString(fileBytes);

// Decode Base64 back to a file
byte[] back = Base64.getDecoder().decode(encoded);
Files.write(Paths.get("output.png"), back);

Frequently asked questions

How do I Base64 encode a string in Java?

Convert the string to bytes, then encode: Base64.getEncoder().encodeToString("Hello, world!".getBytes(StandardCharsets.UTF_8)) returns "SGVsbG8sIHdvcmxkIQ==".

How do I Base64 decode in Java?

Base64.getDecoder().decode(s) returns a byte[]; wrap it with new String(bytes, StandardCharsets.UTF_8) for a string.

How do I do URL-safe Base64?

Use Base64.getUrlEncoder() / getUrlDecoder(), and chain .withoutPadding() to drop the trailing =.

Does Java have built-in Base64 support?

Yes — java.util.Base64 (Java 8+) provides getEncoder(), getUrlEncoder(), and getMimeEncoder(). No external library required.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →