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

相关推荐
@PHARAOH10 分钟前
HOW - Go 开发入门(一)
开发语言·后端·golang
美好的事情能不能发生在我身上7 小时前
Hot100中的:贪心专题
java·数据结构·算法
myloveasuka7 小时前
Java与C++多态访问成员变量/方法 对比
java·开发语言·c++
2301_821700537 小时前
C++编译期多态实现
开发语言·c++·算法
Andya_net7 小时前
Spring | @EventListener事件机制深度解析
java·后端·spring
奥地利落榜美术生灬7 小时前
c++ 锁相关(mutex 等)
开发语言·c++
xixihaha13247 小时前
C++与FPGA协同设计
开发语言·c++·算法
lang201509287 小时前
18 Byte Buddy 进阶指南:解锁 `@Pipe` 注解,实现灵活的方法转发
java·byte buddy
重庆小透明7 小时前
【java基础篇】详解BigDecimal
java·开发语言
ID_180079054738 小时前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json