Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

Java 8: Base64 Encoding and Decoding

Use Java 8’s built-in java.util.Base64 to encode UTF-8 text or raw bytes, select the right Base64 variant, decode safely, and process streams.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Java 8 includes java.util.Base64, so you can encode and decode Base64 without an extra library. For text, convert to bytes with an explicit charset such as UTF-8, then use the matching decoder and charset.

Encode and decode a Java string

This Java 8 example encodes UTF-8 bytes and decodes them back to UTF-8 text:

As an Amazon Associate I earn from qualifying purchases.

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

public class Base64Example {
    public static void main(String[] args) {
        String original = "Hello, Java 8!";

        String encoded = Base64.getEncoder().encodeToString(
                original.getBytes(StandardCharsets.UTF_8));

        String decoded = new String(
                Base64.getDecoder().decode(encoded),
                StandardCharsets.UTF_8);

        System.out.println("Original: " + original);
        System.out.println("Encoded: " + encoded);
        System.out.println("Decoded: " + decoded);
    }
}

The encoded value is SGVsbG8sIEphdmEgOCE=; decoding it produces Hello, Java 8!. The Java 8 Base64 API is part of the standard library.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encode and decode byte arrays

Base64 works on bytes, not characters. If the data is an image, file, compressed content, or other binary payload, encode the original bytes directly and keep the decoded result as bytes:

byte[] data = { 0, 1, 2, 3, 4, 5 };

String encoded = Base64.getEncoder().encodeToString(data);
byte[] decoded = Base64.getDecoder().decode(encoded);

For a byte-array result from encoding, use encode rather than encodeToString:

byte[] encodedBytes = Base64.getEncoder().encode(data);
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);

Do not convert arbitrary binary bytes into a Java string just to encode them; bytes that do not represent text can be changed or misinterpreted by a character decoder.

Choose the Base64 variant that matches the protocol

Use case Encoder Decoder Behavior
Ordinary Base64 Base64.getEncoder() Base64.getDecoder() Uses + and /; output has no line breaks.
URL- or filename-safe Base64 Base64.getUrlEncoder() Base64.getUrlDecoder() Uses - and _ in place of + and /.
MIME-style Base64 Base64.getMimeEncoder() Base64.getMimeDecoder() Encoder wraps lines at up to 76 characters with CRLF separators; decoder ignores characters outside the Base64 alphabet.

Basic Base64 rejects characters outside its alphabet, while MIME decoding is deliberately more permissive. URL-safe Base64 is a distinct variant, not a spelling that should be assumed interchangeable with ordinary Base64. Use the variant expected by the receiving system; the RFC 4648 Base64 specification defines the standard and URL-safe alphabets.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Basic Base64

String encoded = Base64.getEncoder().encodeToString(data);
byte[] decoded = Base64.getDecoder().decode(encoded);

URL-safe Base64

String encoded = Base64.getUrlEncoder().encodeToString(data);
byte[] decoded = Base64.getUrlDecoder().decode(encoded);

MIME Base64

String encoded = Base64.getMimeEncoder().encodeToString(data);
byte[] decoded = Base64.getMimeDecoder().decode(encoded);

Padding: keep it unless the protocol says otherwise

Standard output includes = padding when needed to complete the final Base64 group. For example, TQ==, TWE=, and TWFu encode byte sequences of different lengths. You can omit padding with an encoder configured for that purpose:

String unpadded = Base64.getUrlEncoder()
        .withoutPadding()
        .encodeToString(data);

Use this only when the receiving protocol permits unpadded Base64. Although Java decoders can accept some inputs with omitted final padding, protocol rules—not decoder leniency—should determine what your application sends and accepts. RFC 4648 generally requires padding unless the referring specification says otherwise.

Process larger data with streams

Stream wrappers let you encode or decode as data is read or written, instead of first holding the entire payload in memory. Close the encoding stream so it can finish the final Base64 group and write any required padding.

Encode to an output stream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64StreamEncoding {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try (OutputStream encodedStream = Base64.getEncoder().wrap(output)) {
            encodedStream.write("Hello, Java 8!".getBytes(StandardCharsets.UTF_8));
        }

        String encoded = new String(output.toByteArray(), StandardCharsets.US_ASCII);
        System.out.println(encoded);
    }
}

This example collects the encoded result in memory for display. For a large file, wrap the actual destination stream instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decode from an input stream

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64StreamDecoding {
    public static void main(String[] args) throws IOException {
        byte[] encoded = "SGVsbG8sIEphdmEgOCE=".getBytes(StandardCharsets.US_ASCII);

        try (InputStream decodedStream = Base64.getDecoder().wrap(
                new ByteArrayInputStream(encoded))) {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = decodedStream.read(buffer)) != -1) {
                System.out.write(buffer, 0, count);
            }
        }
    }
}

For larger or repeated operations, the encoder and decoder also provide ByteBuffer and destination-buffer methods; the Java 8 Encoder and Decoder references list their overloads and stream wrappers.

Best Value
Java Programming Java Success Algorithm Java Programmer T-Shirt
  • Java Programming Java Success Algorithm Java Programmer is a perfect present for IT specialist or a computer geek, computer nerd, network engineer. Funny gift idea for a Java coder or programmer, Java script developer, cool gift for an IT professional.
  • Java Programming Java Success Algorithm Java Programmer is a cool gift for JS, Javascript programmers and Web developers. Funny Java Programming gift for husband and also suitable for a wife. Funny Java programmer birthday gift, IT gift for Christmas.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle malformed input and common mistakes

  • Illegal characters or malformed input: Basic and URL-safe decoding can throw IllegalArgumentException. Validate input and handle the exception rather than silently deleting characters.
  • Wrong variant: A URL-safe value can contain - or _. Decode it with getUrlDecoder(), not the basic decoder.
  • Missing or incorrect padding: Do not add or remove = by guesswork. Follow the format’s stated padding rules.
  • Wrong charset: If the source text was encoded as UTF-8, construct the decoded string with UTF-8 too. Using the platform default charset can make results differ between environments.
  • Empty input: An empty byte array encodes to an empty string, and decoding an empty string returns a zero-length array. Your application may still need to reject an empty field.
  • Null input: Null arguments generally result in NullPointerException; validate nullable values before calling the API.
try {
    byte[] decoded = Base64.getDecoder().decode(input);
} catch (IllegalArgumentException ex) {
    // Reject the input or handle it according to the protocol.
}

Do not use MIME decoding merely to make malformed input appear acceptable: its behavior intentionally ignores non-alphabet characters, which can hide unexpected data. RFC 4648 discusses non-alphabet characters and canonical encoding; applications that sign or compare encoded strings should define whether they require canonical output, padding, or a particular alphabet.

UTF-8, size, and security

Use StandardCharsets.UTF_8 when converting text to bytes and back. Calling text.getBytes() without a charset relies on the environment’s default, so different deployments can produce different bytes and therefore different Base64 strings.

Base64 is an encoding, not encryption, hashing, or authentication. Anyone who obtains a Base64 value can decode it. Do not use it to protect passwords or confidential data; use an appropriate password-hashing method for passwords and authenticated encryption for confidential application data.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Base64 maps each group of three input bytes to four output characters, making the encoded representation roughly one-third larger before any line breaks. Avoid it for large payloads when the transport supports binary data directly.

Useful Java 8 API methods

Task Method
Basic, URL-safe, or MIME encoder/decoder getEncoder(), getDecoder(), getUrlEncoder(), getUrlDecoder(), getMimeEncoder(), getMimeDecoder()
Encode to string or bytes encodeToString(byte[]), encode(byte[])
Decode from string or bytes decode(String), decode(byte[])
Wrap streams Encoder.wrap(OutputStream), Decoder.wrap(InputStream)
Omit padding Encoder.withoutPadding()

For a custom MIME line length, Java provides getMimeEncoder(int lineLength, byte[] lineSeparator); the effective length is rounded down to a multiple of four, and a separator containing a Base64 alphabet character is rejected.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.