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

相关推荐
故乡de云20 分钟前
AWS 添加付款方式失败排查清单:卡片、银行风控与账号状态逐项定位
开发语言·php
其美杰布-富贵-李23 分钟前
Spring Boot 依赖注入说明文档
java·spring boot·python
J_yyy27 分钟前
【Qt核心组件类框架】
开发语言·qt
tachibana228 分钟前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
our_times33 分钟前
2026年Java开发者破局指南:Spring AI 2.0 与 Agent 开发实战
java·人工智能·spring
运维行者_42 分钟前
如何查看每个IP的带宽使用情况?NetFlow 技术实战指南
开发语言·网络·分布式·后端·架构·带宽
天天进步20151 小时前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
糖果店的幽灵1 小时前
langgraph的四种state解析
java·前端·javascript·langgraph
杨充1 小时前
4.接口而非实现编程
java·后端·架构
梦梦代码精1 小时前
基于ThinkPHP6 + Vue3的家政预约系统全解析:从LBS定位到自动派单的完整实现
java·docker·开源·php·代码规范