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

相关推荐
yours_Gabriel4 分钟前
【登录认证】JWT令牌
java·开发语言·redis
为美好的生活献上中指10 分钟前
java每日精进 5.11【WebSocket】
java·javascript·css·网络·sql·websocket·网络协议
qq_141826973216 分钟前
python通过curl访问deepseek的API调用案例
java·数据库·python
lyw20561918 分钟前
微服务八股(自用)
java·开发语言
dot to one19 分钟前
Qt 中 QWidget涉及的常用核心属性介绍
开发语言·c++·qt
液态不合群26 分钟前
理解 C# 中的各类指针
java·开发语言·c#
一只码代码的章鱼28 分钟前
Java Spring MVC -01
java·spring·mvc
橙子1991101635 分钟前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin36 分钟前
Kotlin 懒初始化值
android·开发语言·kotlin
Persistence___43 分钟前
SpringBoot中的拦截器
java·spring boot·后端