Base64 Encoding in Java

Java provides built-in support for base64 encoding/decoding.

import java.util.Base64;

public class Base64Encoding {
    public static void main(String[] args) {
        // Here's the string we'll encode/decode.
        String data = "abc123!?$*&()'-=@~";

        // Java supports both standard and URL-compatible
        // base64. Here's how to encode using the standard
        // encoder. The encoder requires a byte array, so we
        // convert our string to that type.
        String sEnc = Base64.getEncoder().encodeToString(data.getBytes());
        System.out.println(sEnc);

        // Decoding may throw an exception, which you can catch
        // if you don't already know the input to be
        // well-formed.
        try {
            byte[] sDec = Base64.getDecoder().decode(sEnc);
            System.out.println(new String(sDec));
        } catch (IllegalArgumentException e) {
            System.out.println("Decoding failed: " + e.getMessage());
        }
        System.out.println();

        // This encodes/decodes using a URL-compatible base64
        // format.
        String uEnc = Base64.getUrlEncoder().encodeToString(data.getBytes());
        System.out.println(uEnc);
        try {
            byte[] uDec = Base64.getUrlDecoder().decode(uEnc);
            System.out.println(new String(uDec));
        } catch (IllegalArgumentException e) {
            System.out.println("Decoding failed: " + e.getMessage());
        }
    }
}

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

$ java Base64Encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In Java, we use the java.util.Base64 class for base64 encoding and decoding. The Base64.getEncoder() and Base64.getDecoder() methods provide standard base64 encoding and decoding, while Base64.getUrlEncoder() and Base64.getUrlDecoder() provide URL-safe encoding and decoding.

The encodeToString() method is used for encoding, which takes a byte array as input. To decode, we use the decode() method, which returns a byte array. We then convert this byte array back to a string for printing.

Note that in Java, decoding can throw an IllegalArgumentException if the input is not properly formatted base64. It’s good practice to catch this exception when decoding.

查看推荐产品

Comments powered by Disqus