Java实现⽂件和base64字符串互转项⽬中遇到需要将图⽚转成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 = "E:\\base2Img\\target\\";
public static void main(String[] args) throws Exception {
String fileStr = getFileStr("E:\\base2Img\\");
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.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回 Base64 编码过的字节数组字符串
de(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(" 不⾏,oops! ");
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 = ad(buff)) != -1) {
out.write(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
return true;
}
}

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