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

相关推荐
2601_9557598811 分钟前
如何识别 Claude API 低价值调用并优化
java
AI科技星14 分钟前
曲率‑挠率与 $\boldsymbol{\omega/c}$ 的关系、精算验证及其物理意义
c语言·开发语言·线性代数·算法·决策树·机器学习·ai科技星
鹿角片ljp1 小时前
Java框架篇:Spring + SpringMVC + SpringBoot + MyBatis深度复习
java·开发语言
Lyra_Infra1 小时前
Java 应用启动脚本 JDK 路径适配优化文档
java·shell
CodeHackerBhx2 小时前
Spring Boot 4 防重复提交:从接口幂等到 Redis 分布式锁的完整实践
java·数据库·spring boot·redis·分布式
xlxxy_2 小时前
外部系统调用SAP接口遇到的一些报错
开发语言·数据库·sap·abap
八角.。2 小时前
方法参数与Debug按键
java·开发语言·jvm
BerryS3N2 小时前
Java在人工智能与大模型时代的深度演进:从工程落地、高性能计算到企业级Agent与RAG架构实战指南
java·人工智能·架构
郝亚军2 小时前
FE1.1S-BQFN24BT可以指定IP端口吗?
开发语言·php
阿里嘎多学长2 小时前
2026-08-04 GitHub 热点项目精选
开发语言·程序员·github·代码托管