杰瑞科技汇

Java byte如何转为base64?

Of course! Let's break down how to work with Java byte arrays and Base64 encoding/decoding. This is a very common task, especially when dealing with binary data like images, files, or encrypted information.

Java byte如何转为base64?-图1
(图片来源网络,侵删)

We'll cover three main aspects:

  1. The java.util.Base64 API: The modern, standard way to handle Base64 in Java.
  2. Encoding a byte[] to a Base64 String.
  3. Decoding a Base64 String back to a byte[].

The java.util.Base64 API

Java 8 introduced a dedicated package, java.util.Base64, for all Base64 operations. This is the recommended approach. It provides an encoder and a decoder, which can be configured for different line-length and URL-safe options.

The main class is java.util.Base64. You typically get an instance of its nested Encoder and Decoder classes.

Class/Method Description
Base64.getEncoder() Returns a standard Base64 encoder. It pads the output with characters to make the length a multiple of 4.
Base64.getUrlEncoder() Returns a URL-safe encoder. It replaces with and with _ and omits padding.
Base64.getMimeEncoder() Returns a MIME encoder. It inserts line breaks (e.g., \n) every 76 characters. Useful for email attachments.
Base64.getDecoder() Returns a standard Base64 decoder.
Base64.getUrlDecoder() Returns a URL-safe decoder.
Base64.getMimeDecoder() Returns a MIME decoder.

Encoding a byte[] to a Base64 String

This is the most common use case. You have binary data in a byte array and you want to represent it as a text String for storage, transmission, or embedding in JSON/XML.

Java byte如何转为base64?-图2
(图片来源网络,侵删)

Example: Encoding a byte[]

Let's take a simple byte array and encode it.

import java.util.Base64;
public class Base64EncoderExample {
    public static void main(String[] args) {
        // 1. Your original data as a byte array
        // Let's use the string "Hello, World!" and convert it to bytes
        String originalString = "Hello, World!";
        byte[] originalBytes = originalString.getBytes();
        System.out.println("Original byte array: " + java.util.Arrays.toString(originalBytes));
        // Output: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
        // 2. Get the Base64 encoder
        Base64.Encoder encoder = Base64.getEncoder();
        // 3. Encode the byte array to a Base64 string
        // The encodeToString() method is the most convenient for this.
        String base64String = encoder.encodeToString(originalBytes);
        System.out.println("Encoded Base64 String: " + base64String);
        // Output: SGVsbG8sIFdvcmxkIQ==
    }
}

Special Case: URL-Safe Encoding

If you need to use the Base64 string in a URL, you should use the URL-safe encoder to avoid issues with special characters.

// ...
Base64.Encoder urlEncoder = Base64.getUrlEncoder();
String urlSafeBase64String = urlEncoder.encodeToString(originalBytes);
System.out.println("URL-Safe Encoded String: " + urlSafeBase64String);
// Output: SGVsbG8sIFdvcmxkIQ==
// (This example is the same because the input didn't produce + or /,
// but for other data like a PNG image, it would be different.)

Decoding a Base64 String back to a byte[]

Now, let's reverse the process. You have a Base64 String and you want to get the original byte array back.

Example: Decoding a Base64 String

import java.util.Base64;
public class Base64DecoderExample {
    public static void main(String[] args) {
        // 1. The Base64 string you want to decode
        String base64String = "SGVsbG8sIFdvcmxkIQ==";
        // 2. Get the Base64 decoder
        Base64.Decoder decoder = Base64.getDecoder();
        // 3. Decode the Base64 string to a byte array
        byte[] decodedBytes = decoder.decode(base64String);
        System.out.println("Decoded byte array: " + java.util.Arrays.toString(decodedBytes));
        // Output: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
        // 4. (Optional) Convert the byte array back to a String to verify
        String decodedString = new String(decodedBytes);
        System.out.println("Decoded String: " + decodedString);
        // Output: Hello, World!
    }
}

Special Case: URL-Safe Decoding

You must use the correct decoder for the type of encoding. If you used getUrlEncoder() to create the string, you must use getUrlDecoder() to decode it.

Java byte如何转为base64?-图3
(图片来源网络,侵删)
// ...
Base64.Decoder urlDecoder = Base64.getUrlDecoder();
byte[] urlDecodedBytes = urlDecoder.decode(base64String);
// The result will be the same as the standard decoder in this case
String urlDecodedString = new String(urlDecodedBytes);
System.out.println("URL-Safe Decoded String: " + urlDecodedString);
// Output: Hello, World!

Complete, Runnable Example

Here is a full example that combines encoding and decoding, including a more realistic binary data example (a small PNG image).

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class CompleteBase64Example {
    public static void main(String[] args) throws IOException {
        // --- Example 1: Simple String ---
        System.out.println("--- Example 1: String ---");
        String textToEncode = "Java 8 makes Base64 easy!";
        byte[] textBytes = textToEncode.getBytes();
        // Encode
        Base64.Encoder encoder = Base64.getEncoder();
        String encodedText = encoder.encodeToString(textBytes);
        System.out.println("Encoded Text: " + encodedText);
        // Decode
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decodedTextBytes = decoder.decode(encodedText);
        String decodedText = new String(decodedTextBytes);
        System.out.println("Decoded Text: " + decodedText);
        System.out.println("Original and Decoded are equal? " + textToEncode.equals(decodedText));
        System.out.println("\n------------------------------------\n");
        // --- Example 2: Binary Data (File) ---
        System.out.println("--- Example 2: Binary File ---");
        // Create a dummy file for this example
        byte[] imageBytes = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; // PNG file header
        Files.write(Paths.get("test.png"), imageBytes);
        // 1. Read the binary file into a byte array
        byte[] fileBytes = Files.readAllBytes(Paths.get("test.png"));
        System.out.println("Original file has " + fileBytes.length + " bytes.");
        // 2. Encode the file's byte array to Base64
        String encodedFile = encoder.encodeToString(fileBytes);
        System.out.println("Encoded File (first 50 chars): " + encodedFile.substring(0, 50) + "...");
        // 3. Decode the Base64 string back to a byte array
        byte[] decodedFileBytes = decoder.decode(encodedFile);
        System.out.println("Decoded byte array has " + decodedFileBytes.length + " bytes.");
        // 4. (Optional) Write the decoded bytes back to a new file
        Files.write(Paths.get("decoded_test.png"), decodedFileBytes);
        System.out.println("Decoded file written as 'decoded_test.png'");
    }
}

Important Considerations

  • Character Encoding: When converting a String to a byte[] (e.g., myString.getBytes()), the platform's default character set is used. This can lead to inconsistencies. For predictable results, always specify a character set, like StandardCharsets.UTF-8.
    // Good practice
    byte[] bytes = myString.getBytes(StandardCharsets.UTF_8);
    String str = new String(byteArray, StandardCharsets.UTF_8);
  • Padding: The standard Base64 encoder pads the output with characters to ensure the string length is a multiple of 4. The URL-safe encoder omits this padding. Most decoders can handle both padded and unpadded input, but it's best to be consistent.
  • Line Breaks: The MIME encoder adds line breaks. If you decode a MIME-encoded string, you should use the MimeDecoder to handle these line breaks correctly.
分享:
扫描分享到社交APP
上一篇
下一篇