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"为实际文件路径,并在编码后的字符串保存时指定合适的输出文件路径。

相关推荐
m0_71676523几秒前
C++提高编程--STL常用容器(set/multiset、map/multimap容器)详解
java·开发语言·c++·经验分享·学习·青少年编程·visual studio
qqty121714 分钟前
springboot+mybaties项目中扫描不到@mapper注解的解决方法
java·spring boot·mybatis
灵魂猎手22 分钟前
14. MyBatis XML 热更新实战:告别重启烦恼
java·mybatis
程途知微22 分钟前
AQS 同步器——Java 并发框架的核心底座全解析
java·后端
froginwe1127 分钟前
Bootstrap4 折叠组件使用指南
开发语言
sunwenjian88628 分钟前
SpringBean的生命周期
java·开发语言
毕设源码-赖学姐1 小时前
【开题答辩全过程】以 基于Java的游泳馆会员管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
侠客行03171 小时前
Tomcat 网络I/O模型浅析
java·tomcat·源码阅读
Yilena1 小时前
带你轻松学习LangChain4j
java·学习·langchain
皙然1 小时前
深入拆解MESI协议:从原理到实战,搞懂CPU缓存一致性的核心机制
java·缓存