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

相关推荐
前端炒粉1 分钟前
简易实现ssr
开发语言·前端·javascript
库克克7 分钟前
【C++】 unordered_map 与unordered_set
开发语言·c++
huahailing102412 分钟前
Spring Boot 集成 XXL-Job 完整实现方案(支持动态CRUD)
java·spring boot·后端
薛定谔的猫-菜鸟程序员31 分钟前
基于 Electron 的本地短视频解析与下载工具:架构设计与工程实践
java·electron·音视频
雪的季节1 小时前
人工智能 AI 5问
开发语言
李迟1 小时前
一种轻量级C++ CSV文件读写库的实现方案
开发语言·c++
音符犹如代码1 小时前
Arthas Profiler 火焰图实战:CPU 热点在哪一目了然
java·jvm·spring boot
小园子的小菜1 小时前
Java 并发编程:线程安全队列全解 —— 阻塞与非阻塞实现原理及源码深度剖析
java·开发语言
好好沉淀1 小时前
Windows 下升级 Maven 3.6.1 到 3.9.9 踩坑全记录
java·windows·maven
CodexDave2 小时前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理