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

相关推荐
a诠释淡然1 分钟前
C++模板元编程—现代C++的黑魔法
开发语言·c++
极客先躯5 分钟前
高级java每日一道面试题-2026年02月04日-实战篇[Docker]-如何在容器之间共享数据?
java·运维·网络·docker·容器·自动化·高级面试题
真实的菜5 分钟前
微服务架构痛点
java·微服务·架构
小楊不秃头6 分钟前
Spring:Bean的存储
java·spring·bean
西凉的悲伤7 分钟前
多线程彻底掌握 CompletableFuture:从入门到项目实战
java·多线程·future·completable·异步
用户298698530147 分钟前
Java 中的 HTML 解析:从文件读取、URL 抓取到数据提取
java·后端
plainGeekDev7 分钟前
ContentProvider → Room + Repository
android·java·kotlin
charlie1145141919 分钟前
现代C++工程:constexpr 基础:编译期求值的艺术
开发语言·c++
plainGeekDev12 分钟前
SQLite 手动升级 → Room Migration
android·java·kotlin
MemoriKu13 分钟前
Flutter 相册 APP 视频模态稳定化实战:从视频抽帧、Embedding 元数据到 Android 真机启动修复
android·开发语言·前端·flutter·架构·音视频·embedding