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

相关推荐
柒.梧.3 分钟前
Java集合核心知识点深度解析:数组与集合区别、ArrayList原理及线程安全问题
java·开发语言·python
0 0 04 分钟前
洛谷P4427 [BJOI2018] 求和 【考点】:树上前缀和
开发语言·c++·算法·前缀和
web3.08889995 分钟前
使用PHP采集数据的完整技术文章,涵盖多种场景和最佳实践
开发语言·php
柒.梧.11 分钟前
Java基础高频面试题(含详细解析+易错点,面试必看)
java·开发语言·面试
佩奇大王12 分钟前
P593 既约分数
java·开发语言·算法
小同志0017 分钟前
软件测试周期 与 BUG
java·软件测试·bug·软件测试周期·bug等级
Han.miracle18 分钟前
Spring IoC 容器与 Bean 管理核心考点解析
java·ioc·di
polaris063019 分钟前
Java集合进阶
java·开发语言
AsDuang25 分钟前
Python 3.12 MagicMethods - 49 - __imatmul__
开发语言·python
tant1an33 分钟前
Spring Boot 基础入门:从核心配置到 SSMP 整合实战
java·数据库·spring boot·sql·spring