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

相关推荐
9稳4 分钟前
基于PLC的生产线自动升降机设计
开发语言·网络·数据库·嵌入式硬件·plc
我是唐青枫11 分钟前
C#.NET ReaderWriterLockSlim 深入解析:读写锁原理、升级锁与使用边界
开发语言·c#·.net
4ever.ov013 分钟前
定时器/时间轮
开发语言·c++·c·muduo·llinux
WarrenMondeville18 分钟前
4.Unity面向对象-接口隔离原则
java·unity·接口隔离原则
zb2006412018 分钟前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
啥咕啦呛19 分钟前
java打卡学习3:ArrayList扩容机制
java·python·学习
编程之升级打怪21 分钟前
用排他锁来实现Python语言的变量值更新
开发语言·python
rrrjqy21 分钟前
Java基础篇(二)
java·开发语言
我命由我1234527 分钟前
React - React 配置代理、搜索案例(Fetch + PubSub)、React 路由基本使用、NavLink
开发语言·前端·javascript·react.js·前端框架·html·ecmascript
沐知全栈开发28 分钟前
R 循环:深度解析与高效运用
开发语言