Java8中文件轉Base64和Base64轉文件
有幾個項目中,都需要將圖片或者數字證書的文件轉為Base64,昨天寫代碼的時候,發現在jdk8中本就含有關于Base64的API。從此后不再需要其他的jar包來轉換Base64了!!!
據說是JDK8加入的。
先是將文件轉為Base64:
public String encryptToBase64(String filePath) {
if (filePath == null) {
return null;
}
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
if (filePath == null) {
return null;
}
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Files、Paths類是JDK7里加入的,讀取文件不再需要調用IO包里的FileInputStream,簡單便捷。
字符串參數filePath是文件的路徑。
首先是將文件讀成二進制碼,然后通過Base64.getEncoder().encodeToString()方法將二進制碼轉換為Base64值。
然后是將Base64轉為文件:
public String decryptByBase64(String base64, String filePath) {
if (base64 == null && filePath == null) {
return "生成文件失敗,請給出相應的數據。";
}
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64),StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
return "指定路徑下生成文件成功!";
}
if (base64 == null && filePath == null) {
return "生成文件失敗,請給出相應的數據。";
}
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64),StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
return "指定路徑下生成文件成功!";
}
字符串參數base64指的是文件的Base64值,filePath是指的文件將要保存的位置。
通過Files.write()方法輕松將文件寫入指定位置,不再調用FileOutStream方法。
第三個參數StandardOpenOption.CREATE是處理文件的方式,我設置的是不管路徑下有或沒有,都創建這個文件,有則覆蓋。
在StandardOpenOption類中有很多參數可調用,不再累贅。
posted on 2021-01-07 09:44 paulwong 閱讀(3858) 評論(0) 編輯 收藏 所屬分類: J2SE