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

相关推荐
慧一居士4 分钟前
SpringCloud 微服务Feigin 用的完整调用端和被调用的示例
java·spring cloud
我命由我1234511 分钟前
Jetpack Room - Room 查询返回列表无需判空、LIKE 关键字
android·java·开发语言·java-ee·android jetpack·android-studio·android runtime
goodluckyaa21 分钟前
Warp shuffle函数
开发语言
j7~22 分钟前
【C++】STL--Vector容器--拆析解剖Vector的实现以及Vector的底层详解(1)
开发语言·c++·vector·迭代器失效·迭代器的使用
平安的平安24 分钟前
传统Java工程师第一次用飞算JavaAI生成SpringBoot项目
java
csjane107928 分钟前
Redisson 限流原理
java·redis
xxwl58528 分钟前
Python语言初步认识(1)
开发语言·python·学习
一个做软件开发的牛马29 分钟前
MyBatis 从零实战:完整搭建可运行 Demo,注解与 XML 双模式开发详解
java·后端
z落落32 分钟前
C# FileStream文件流读取文件
开发语言·c#
砍材农夫35 分钟前
python环境|conda安装和使用(1)
开发语言·后端·python·conda