在 Java 的 JDK 中,Base64
类提供了用于处理 Base64 编码和解码的工具。以下是一个示例,演示如何使用 Base64
类来进行文件内容的编码和解码:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
// 1. 读取文件内容
Path filePath = Paths.get("path/to/your/file.txt");
String fileContent = readFile(filePath);
// 2. 使用 Base64 编码
String encodedContent = base64Encode(fileContent);
System.out.println("Encoded Content:\n" + encodedContent);
// 3. 使用 Base64 解码
String decodedContent = base64Decode(encodedContent);
System.out.println("Decoded Content:\n" + decodedContent);
}
private static String readFile(Path filePath) {
try {
return new String(Files.readAllBytes(filePath));
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String base64Encode(String content) {
byte[] encodedBytes = Base64.getEncoder().encode(content.getBytes());
return new String(encodedBytes);
}
private static String base64Decode(String encodedContent) {
byte[] decodedBytes = Base64.getDecoder().decode(encodedContent);
return new String(decodedBytes);
}
}
请替换示例中的 path/to/your/file.txt
为实际的文件路径。这个示例中,readFile
方法用于读取文件内容,base64Encode
方法使用 Base64 编码,而 base64Decode
方法用于解码。
注意: 在实际使用中,请确保文件内容不过大,否则可能会导致内存问题。如果处理大文件,你可能需要分块读取和编码/解码。