base64文件流互转
一 前言
本篇文章只是在工作中用到了,知识追寻者随便记录一下,以备不时只须,有用你就用吧;
知识追寻者(Inheriting the spirit of open source, Spreading technology knowledge;);
二 base编码
Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,可以使用64个可打印字符来表示二进制数据的方法;
更多参考
https://blog.csdn.net/qq_20545367/article/details/79538530
https://blog.csdn.net/wufaliang003/article/details/79573512
一般文件进行base64编码后都有个前缀声明为base64图片;比如图片的编码如下
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........
真正的编码内容是data:image/png;base64,后的内容;
iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........
三 base64文件编码解码
3.1 编码
编码后返回编码的字符串
/* *
* @Author lsc
* <p> base64编码 </p>
* @Param [path]
* @Return java.lang.String 返回编码后的字符串
*/
public static String encodeBase64File(String path){
// 读取文件
File file = new File(path);
// 声明输入流
FileInputStream inputFile = null;
// 声明字节数组
byte[] buffer = null;
try {
inputFile = new FileInputStream(file);
// 创建字节数组
buffer = new byte[(int) file.length()];
// 输入
inputFile.read(buffer);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 解码
return new BASE64Encoder()
.encode(buffer);
}
也可以将字节数组放入输入流进行对象存储
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
3.2 解码
将编码后的字符串重新转为文件
/* *
* @Author lsc
* <p> base64解码 </p>
* @Param [base64Code, targetPath] 将编码后的字符串解码为文件
* @Return void
*/
public static void decodeBase64File(String base64Code, String targetPath) {
// 输出流
FileOutputStream out =null;
// 将base 64 转为字节数字
byte[] buffer = new byte[0];
try {
buffer = new BASE64Decoder().decodeBuffer(base64Code);
// 创建输出流
out = new FileOutputStream(targetPath);
// 输出
out.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.3测试示例
@Test
public void test(){
try {
// 文件路径
String filePath = "C:\\mydata\\generator\\世界地图.png";
// 编码
String encodeBase64File = encodeBase64File(filePath);
// 剔除base64声明头
String code = encodeBase64File.replace("data:image/png;base64,", "");
//解码
decodeBase64File(code,"C:\\mydata\\generator\\base64.png");
} catch (Exception e) {
e.printStackTrace();
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库