Java如何实现文件和base64字符串互转呢?
下文笔者讲述文件和base64互相转换的方法分享,如下所示
Base64字符串和文件的互转示例
文件和Base64字符串互转的实现思路
1.引入相应的jar包
2.文件转字节数组
使用BASE64Encoder的方法即可实现字节数组转Base64
使用BASE64Decoder对象中的方法即可转换为字节数组
然后再转换为文件
例:Base64字符串和文件的互转示例
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.13</version>
</dependency>
//编写相应的转换工具类
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64FileUtil {
private static String targetFilePath = "D:\\tmp.txt";
public static void main(String[] args) throws Exception {
String fileStr = getFileStr("D:\\tmp.txt");
System.out.println("fileStr ===" + fileStr);
System.out.println(generateFile(fileStr, targetFilePath));
System.out.println("end");
}
/**
* 文件转化成base64字符串
* 将文件转化为字节数组字符串,并对其进行Base64编码处理
*/
public static String getFileStr(String filePath) {
InputStream in = null;
byte[] data = null;
// 读取文件字节数组
try {
in = new FileInputStream(filePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回 Base64 编码过的字节数组字符串
return encoder.encode(data);
}
/**
* base64字符串转化成文件,可以是JPEG、PNG、TXT和AVI等等
*
* @param base64FileStr
* @param filePath
* @return
* @throws Exception
*/
public static boolean generateFile(String base64FileStr, String filePath) throws Exception {
// 数据为空
if (base64FileStr == null) {
System.out.println("没有文件任何信息!");
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码,对字节数组字符串进行Base64解码并生成文件
byte[] byt = decoder.decodeBuffer(base64FileStr);
for (int i = 0, len = byt.length; i < len; ++i) {
// 调整异常数据
if (byt[i] < 0) {
byt[i] += 256;
}
}
OutputStream out = null;
InputStream input = new ByteArrayInputStream(byt);
try {
// 生成指定格式的文件
out = new FileOutputStream(filePath);
byte[] buff = new byte[1024];
int len = 0;
while ((len = input.read(buff)) != -1) {
out.write(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
return true;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


