在Java中,可以使用java.util.Base64类对文件内容进行Base64加密和解密。下面是对文件内容进行Base64加密和解密的示例代码:
java Copy code
import java.io.*;
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) throws IOException {
// 加密文件内容并保存到目标文件
encodeFileContentToBase64("path/to/source_file.txt", "path/to/encoded_file.txt");
System.out.println("File content encoded and saved.");
// 解密文件内容并保存到目标文件
decodeBase64ToFileContent("path/to/encoded_file.txt", "path/to/decoded_file.txt");
System.out.println("File content decoded and saved.");
}
public static void encodeFileContentToBase64(String sourceFilePath, String encodedFilePath) throws IOException {
byte[] fileContent = Files.readAllBytes(Paths.get(sourceFilePath));
byte[] encodedContent = Base64.getEncoder().encode(fileContent);
Files.write(Paths.get(encodedFilePath), encodedContent);
}
public static void decodeBase64ToFileContent(String encodedFilePath, String decodedFilePath) throws IOException {
byte[] encodedContent = Files.readAllBytes(Paths.get(encodedFilePath));
byte[] decodedContent = Base64.getDecoder().decode(encodedContent);
Files.write(Paths.get(decodedFilePath), decodedContent);
}
}
上述示例代码中,encodeFileContentToBase64()方法读取源文件的内容,然后使用Base64.getEncoder().encode()方法将文件内容进行Base64编码,并将编码后的内容写入目标文件。
decodeBase64ToFileContent()方法读取Base64编码文件的内容,然后使用Base64.getDecoder().decode()方法将其解码为原始字节数组,并将解码后的内容写入目标文件。
请注意替换示例代码中的文件路径(sourceFilePath、encodedFilePath、decodedFilePath)为实际文件路径,并确保读取和写入文件的权限。