Java Base64 加密文件
在 Java 中,可以使用 java.util.Base64 类来对文件进行 Base64 编码(加密),以下是几种实现方式:

使用 Java 8+ 的 Base64 类
import java.io.*;
import java.util.Base64;
public class FileBase64Encoder {
public static void main(String[] args) {
String inputFile = "input.txt"; // 要编码的文件路径
String outputFile = "output.b64"; // 输出的Base64文件路径
try {
// 读取原始文件
File file = new File(inputFile);
byte[] fileContent = new byte[(int) file.length()];
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(fileContent);
}
// 进行Base64编码
String encodedString = Base64.getEncoder().encodeToString(fileContent);
// 将编码结果写入文件
try (FileWriter writer = new FileWriter(outputFile)) {
writer.write(encodedString);
}
System.out.println("文件已成功编码为Base64并保存到 " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用流式处理(适用于大文件)
import java.io.*;
import java.util.Base64;
public class LargeFileBase64Encoder {
public static void main(String[] args) {
String inputFile = "large_file.zip"; // 要编码的大文件
String outputFile = "large_file.b64"; // 输出的Base64文件
try (
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
Base64.Encoder encoder = Base64.getEncoder()
) {
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
byte[] encodedBytes = encoder.encode(buffer, 0, bytesRead);
bos.write(encodedBytes);
}
System.out.println("大文件已成功编码为Base64并保存到 " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
解码 Base64 文件
如果你需要将 Base64 编码的文件解码回原始文件:
import java.io.*;
import java.util.Base64;
public class FileBase64Decoder {
public static void main(String[] args) {
String inputFile = "output.b64"; // Base64编码的文件
String outputFile = "decoded.txt"; // 解码后的输出文件
try (
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
FileOutputStream fos = new FileOutputStream(outputFile);
Base64.Decoder decoder = Base64.getDecoder()
) {
StringBuilder base64String = new StringBuilder();
String line;
// 读取所有Base64内容(去除换行符)
while ((line = reader.readLine()) != null) {
base64String.append(line);
}
// 解码并写入文件
byte[] decodedBytes = decoder.decode(base64String.toString());
fos.write(decodedBytes);
System.out.println("Base64文件已成功解码并保存到 " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
-
内存使用:对于大文件,方法一可能会消耗大量内存,因为需要一次性读取整个文件,方法二更适合处理大文件。
-
换行符:Base64编码通常每76个字符插入一个换行符,如果需要处理包含换行符的Base64文件,解码时需要先去除所有空白字符。
-
文件类型:Base64编码适用于任何二进制文件,不仅仅是文本文件。
(图片来源网络,侵删) -
Java版本:上述代码需要Java 8或更高版本,因为
java.util.Base64是在Java 8中引入的。 -
性能:对于非常大的文件,考虑使用NIO(New I/O)类来提高性能。
希望这些方法能帮助你实现Java中的文件Base64编码和解码!

