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

在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 {

// 读取文件内容并进行Base64编码

String encodedString = encodeFileToBase64("path/to/file.txt");

System.out.println("Encoded string: " + encodedString);

// 将Base64编码的字符串解码并写入文件

decodeBase64ToFile(encodedString, "decoded_file.txt");

System.out.println("File decoded and saved.");

}

public static String encodeFileToBase64(String filePath) throws IOException {

byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

return Base64.getEncoder().encodeToString(fileContent);

}

public static void decodeBase64ToFile(String base64String, String outputFilePath) throws IOException {

byte[] decodedBytes = Base64.getDecoder().decode(base64String);

Path outputPath = Paths.get(outputFilePath);

Files.write(outputPath, decodedBytes);

}

}

上述示例代码中,encodeFileToBase64()方法用于将文件内容读取为字节数组,然后使用Base64.getEncoder().encodeToString()方法将字节数组进行Base64编码,并返回编码后的字符串。

decodeBase64ToFile()方法接收一个Base64编码的字符串,使用Base64.getDecoder().decode()方法将其解码为字节数组,然后使用Files.write()方法将字节数组写入指定的文件。

请注意替换示例代码中的"path/to/file.txt"为实际文件路径,并在编码后的字符串保存时指定合适的输出文件路径。

相关推荐
佟格湾3 分钟前
聊透多线程编程-线程池-6.C# APM(异步编程模型)
开发语言·后端·c#·多线程
xrkhy11 分钟前
面向对象高级(1)
java·开发语言
小镇学者17 分钟前
【js】nvm1.2.2 无法下载 Node.js 15及以下版本
开发语言·javascript·node.js
五行星辰24 分钟前
Spring定时任务修仙指南:从@Scheduled到分布式调度的终极奥义
java·后端·spring
昂子的博客29 分钟前
热门面试题第15天|最大二叉树 合并二叉树 验证二叉搜索树 二叉搜索树中的搜索
java·数据结构·算法
东方窅瞳32 分钟前
Bash语言的哈希表
开发语言·后端·golang
HarrisHaword1 小时前
JAVA 导出 word
java·开发语言·word
PingdiGuo_guo1 小时前
C++指针(四)万字图文详解!
开发语言·c++
s9123601011 小时前
Rust Command无法执行*拓展解决办法
开发语言·后端·rust
pk_xz1234561 小时前
MATLAB编写的机械臂控制仿真程序,它主要实现了对一个二连杆机械臂的运动控制仿真,比较了PID控制和非线性模型预测控制两种方法在机械臂轨迹跟踪任务中的性能
开发语言·matlab