java中如何对文件内容进行Base64加密和解密实例?

172 篇文章 6 订阅

在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)为实际文件路径,并确保读取和写入文件的权限。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值