杰瑞科技汇

Java中Base64编码器如何使用?

Of course! Here is a comprehensive guide on how to use Base64 encoding in Java, covering the modern java.util.Base64 API introduced in Java 8, as well as the older, deprecated sun.misc API.

Java中Base64编码器如何使用?-图1
(图片来源网络,侵删)

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

Since Java 8, the standard library includes a robust and easy-to-use java.util.Base64 class. This is the recommended approach for all new code. It provides two main encoders/decoders:

  1. Basic Encoder/Decoder: Standard Base64 encoding. It does not add any line separators and uses the standard alphabet (A-Z, a-z, 0-9, , ). It pads the output with characters if the input length is not a multiple of 3.
  2. URL and Filename Safe Encoder/Decoder: Similar to the basic version, but replaces with and with _. This is ideal for using Base64 in URLs, filenames, or other contexts where these characters have special meaning.

Basic Encoding and Decoding

This is the most common use case.

Encoding a String to Base64

import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64EncoderExample {
    public static void main(String[] args) {
        String originalString = "Hello, World! This is a test.";
        // 1. Get the Base64 encoder
        Base64.Encoder encoder = Base64.getEncoder();
        // 2. Encode the string to a byte array and then to a Base64 string
        // It's best practice to specify the character set (e.g., UTF-8)
        byte[] bytesToEncode = originalString.getBytes(StandardCharsets.UTF_8);
        String encodedString = encoder.encodeToString(bytesToEncode);
        System.out.println("Original String: " + originalString);
        System.out.println("Encoded String:  " + encodedString);
    }
}

Output:

Original String: Hello, World! This is a test.
Encoded String:  SGVsbG8sIFdvcmxkISBUaGlzIGlzIGEgdGVzdC4=

Decoding a Base64 String to String

import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64DecoderExample {
    public static void main(String[] args) {
        String encodedString = "SGVsbG8sIFdvcmxkISBUaGlzIGlzIGEgdGVzdC4=";
        // 1. Get the Base64 decoder
        Base64.Decoder decoder = Base64.getDecoder();
        // 2. Decode the Base64 string to a byte array
        byte[] decodedBytes = decoder.decode(encodedString);
        // 3. Convert the byte array back to a string
        String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
        System.out.println("Encoded String:  " + encodedString);
        System.out.println("Decoded String: " + decodedString);
    }
}

Output:

Java中Base64编码器如何使用?-图2
(图片来源网络,侵删)
Encoded String:  SGVsbG8sIFdvcmxkISBUaGlzIGlzIGEgdGVzdC4=
Decoded String: Hello, World! This is a test.

URL and Filename Safe Encoding and Decoding

This is useful when the Base64 string will be used in a URL or as a filename.

import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64UrlExample {
    public static void main(String[] args) {
        String originalString = "https://www.example.com/path?name=John Doe&role=admin";
        // 1. Get the URL-safe encoder
        Base64.Encoder urlEncoder = Base64.getUrlEncoder();
        // 2. Encode the string
        String encodedUrlString = urlEncoder.encodeToString(originalString.getBytes(StandardCharsets.UTF_8));
        System.out.println("Original URL:   " + originalString);
        System.out.println("URL-Safe Encoded: " + encodedUrlString);
        // 3. Get the URL-safe decoder
        Base64.Decoder urlDecoder = Base64.getUrlDecoder();
        // 4. Decode the string
        byte[] decodedBytes = urlDecoder.decode(encodedUrlString);
        String decodedUrlString = new String(decodedBytes, StandardCharsets.UTF_8);
        System.out.println("Decoded URL:    " + decodedUrlString);
    }
}

Output: Notice how , , and are replaced.

Original URL:   https://www.example.com/path?name=John Doe&role=admin
URL-Safe Encoded: aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20vcGF0aD9uYW1lPUpvaG4gRG9lJ3JvbGU9YWRtaW4=
Decoded URL:    https://www.example.com/path?name=John Doe&role=admin

Encoding and Decoding Byte Arrays

You can also work directly with byte arrays, which is more efficient for large files or binary data.

import java.util.Base64;
public class Base64ByteArrayExample {
    public static void main(String[] args) {
        // Original byte array
        byte[] originalBytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // Encoder
        Base64.Encoder encoder = Base64.getEncoder();
        byte[] encodedBytes = encoder.encode(originalBytes);
        System.out.println("Encoded Bytes (Base64): " + new String(encodedBytes));
        // Decoder
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decodedBytes = decoder.decode(encodedBytes);
        System.out.println("Decoded Bytes (length): " + decodedBytes.length);
        // To print the content: System.out.println(Arrays.toString(decodedBytes));
    }
}

Output:

Java中Base64编码器如何使用?-图3
(图片来源网络,侵删)
Encoded Bytes (Base64): AQIDBAUGBwgJCgw=
Decoded Bytes (length): 10

Handling Mismatched Padding

If you receive a Base64 string that might be missing padding characters (), you can use the withoutPadding() method.

import java.util.Base64;
public class Base64PaddingExample {
    public static void main(String[] args) {
        // String without padding
        String encodedStringNoPadding = "YWJjZA";
        // This would throw an IllegalArgumentException:
        // byte[] decoded = Base64.getDecoder().decode(encodedStringNoPadding);
        // Use the encoder without padding to see what it looks like
        String encodedWithoutPadding = Base64.getEncoder().withoutPadding().encodeToString("abcd".getBytes());
        System.out.println("Encoded without padding: " + encodedWithoutPadding); // Output:YWJjZA
        // To decode a string that might be missing padding, use a tolerant decoder
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            byte[] decodedBytes = decoder.decode(encodedStringNoPadding);
            System.out.println("Decoded successfully: " + new String(decodedBytes));
        } catch (IllegalArgumentException e) {
            System.out.println("Failed to decode with padding: " + e.getMessage());
        }
    }
}

Output:

Encoded without padding: YWJjZA
Decoded successfully: abcd

Note: The standard Base64.getDecoder() is actually tolerant to missing padding, so this example is more for illustration. The IllegalArgumentException is typically thrown for invalid characters.


The Old & Deprecated Way: sun.misc.BASE64Encoder

Before Java 8, this was the common way to do Base64 in the core Java library. You should avoid using this in new code because:

  • It's not part of the official public API.
  • It's in the sun.misc package, which is internal to Oracle's JDK and can change or be removed without notice.
  • It's generally less performant.

However, you might encounter it in older codebases.

Example (for reference only)

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class LegacyBase64Example {
    public static void main(String[] args) {
        String originalString = "This is a legacy example.";
        // --- ENCODING ---
        BASE64Encoder encoder = new BASE64Encoder();
        String encodedString = encoder.encode(originalString.getBytes());
        System.out.println("Original String: " + originalString);
        System.out.println("Encoded String:  " + encodedString);
        // --- DECODING ---
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] decodedBytes = decoder.decodeBuffer(encodedString);
            String decodedString = new String(decodedBytes);
            System.out.println("Decoded String: " + decodedString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Summary: Which One to Use?

Feature java.util.Base64 (Recommended) sun.misc.BASE64Encoder (Deprecated)
Availability Java 8 and later Pre-Java 8 (JDK 1.1+)
Package java.util (Standard API) sun.misc (Internal API)
Encoders getEncoder(), getUrlEncoder(), getMimeEncoder() new BASE64Encoder()
Decoders getDecoder(), getUrlDecoder(), getMimeDecoder() new BASE64Decoder()
Line Breaks getMimeEncoder() for MIME standard line breaks None by default
Padding withoutPadding() option Always pads with
Exception Handling IllegalArgumentException for bad input IOException for decoding errors
Recommendation Always use this for new projects. Avoid. Only for maintaining old code.
分享:
扫描分享到社交APP
上一篇
下一篇