基于基于Java实现文件和实现文件和base64字符串转换字符串转换
主要介绍了基于Java实现文件和base64字符串转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作
具有一定的参考学习价值,需要的朋友可以参考下
这篇文章主要介绍了基于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\test.txt";
public static void main(String[] args) throws Exception {
String fileStr = getFileStr("E:\base2Img\big test.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 {
评论5