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

相关推荐
lisin-lee-cooper1 分钟前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-9 分钟前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
Kyrie_kk9 分钟前
Java--TimeUnit时间单位枚举类(时间单位规范)
java·后端
jayson.h24 分钟前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python
念何架构之路29 分钟前
beego总体架构与工程结构
java·架构·beego
qq_3227627533 分钟前
一个接口从能用到稳定,中间差的到底是什么
服务器·开发语言·lua·接口·fastapi·请求
典典分享指南37 分钟前
用飞书多维表格搭建内容管理看板
java·python·r语言·composer·symfony
Data_Journal42 分钟前
Scrapyd:分步教程
开发语言·python·microsoft·golang·编辑器·html·iphone
离陌在学C#1 小时前
C# 异步编程:从 async/await 到 Task 实战指南
开发语言·数据库·c#
羚尔2 小时前
C语言数组
c语言·开发语言