開發環境:
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);
}
大功告成