开发环境:
JDK8:
由于之前没有接触过Base64,因此在使用的时候,虽然从网上找了一部分例子,不过 发现在项目中却不能使用,原因是自己的项目中没有对应的jar包。
后来才发现,原来在jdk1.6以后的版本中,就已经把Base64的一些方法给集成了,虽然不用重新导入jar包,不过关于Base64的一些使用方法也都改变了。
下面是我遇到了几种情况:
<1>
将 file 转化为 Base64
/*将 file 转化为 Base64/
public static String fileToBase64(String path) {
File file = new File(path);
FileInputStream inputFile;
try {
inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return Base64.getEncoder().encodeToString(buffer);
} catch (Exception e) {
throw new RuntimeException("文件路径无效\n" + e.getMessage());
}
}
<2>
将Base64 转换为file文件
/*将Base64 转换为file文件/
public static boolean base64ToFile(String base64, String path) {
byte[] buffer;
try {
buffer = Base64.getDecoder().decode(base64);
FileOutputStream out = new FileOutputStream(path);
out.write(buffer);
out.close();
return true;
} catch (Exception e) {
throw new RuntimeException("base64字符串异常或地址异常\n" + e.getMessage());
}
}
对以上两个方法的调用
main方法
public static void main(String[] args) {
// 将文件转换为Base64
String path1 = "D:/temp/1.pdf";
String result = Base64deom.fileToBase64(path1);
System.out.println("该文件的Base64:"+result);
// 将Base64转换为文件
String path = "D:/temp/copy1.pdf";
String base64 = result;
Boolean res = Base64deom.base64ToFile(base64, path);
System.out.println(res);
}
欢迎关注本人个人公众号,交流更多技术信息