base64⽂件流互转
⼀前⾔
本篇⽂章只是在⼯作中⽤到了,知识追寻者随便记录⼀下,以备不时只须,有⽤你就⽤吧;
知识追寻者(Inheriting the spirit of open source, Spreading technology knowledge;);
⼆ base编码
Base64是⽹络上最常见的⽤于传输8Bit字节码的编码⽅式之⼀,可以使⽤64个可打印字符来表⽰⼆进制数据的⽅法;更多参考
⼀般⽂件进⾏base64编码后都有个前缀声明为base64图⽚;⽐如图⽚的编码如下
data:image/png;
真正的编码内容是data:image/png;base64,后的内容;
<
三 base64⽂件编码解码
3.1 编码
编码后返回编码的字符串
/* *
go 字符串转数组* @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()];
// 输⼊
} 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 = place("data:image/png;base64,", "");            //解码
decodeBase64File(code,"C:\\mydata\\generator\\base64.png");
} catch (Exception e) {
e.printStackTrace();
}
}
四 base64在线转换⼯具

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。