一 前言
本篇文章只是在工作中用到了,知識追尋者隨便記錄一下,以備不時只須,有用你就用吧;
知識追尋者(Inheriting the spirit of open source, Spreading technology knowledge;);
二 base編碼
Base64是網絡上最常見的用於傳輸8Bit字節碼的編碼方式之一,可以使用64個可打印字符來表示二進制數據的方法;
更多參考
https://blog.csdn.net/qq_20545367/article/details/79538530
https://blog.csdn.net/wufaliang003/article/details/79573512
一般文件進行base64編碼后都有個前綴聲明為base64圖片;比如圖片的編碼如下
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........
真正的編碼內容是data:image/png;base64,后的內容;
iVBORw0KGgoAAAANSUhEUgAAB3AAAAPP...........
三 base64文件編碼解碼
3.1 編碼
編碼后返回編碼的字符串
/* *
* @Author lsc
* <p> base64編碼 </p>
* @Param [path]
* @Return java.lang.String 返回編碼后的字符串
*/
public static String encodeBase64File(String path){
// 讀取文件
File file = new File(path);
// 聲明輸入流
FileInputStream inputFile = null;
// 聲明字節數組
byte[] buffer = null;
try {
inputFile = new FileInputStream(file);
// 創建字節數組
buffer = new byte[(int) file.length()];
// 輸入
inputFile.read(buffer);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
inputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 解碼
return new BASE64Encoder()
.encode(buffer);
}
也可以將字節數組放入輸入流進行對象存儲
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
3.2 解碼
將編碼后的字符串重新轉為文件
/* *
* @Author lsc
* <p> base64解碼 </p>
* @Param [base64Code, targetPath] 將編碼后的字符串解碼為文件
* @Return void
*/
public static void decodeBase64File(String base64Code, String targetPath) {
// 輸出流
FileOutputStream out =null;
// 將base 64 轉為字節數字
byte[] buffer = new byte[0];
try {
buffer = new BASE64Decoder().decodeBuffer(base64Code);
// 創建輸出流
out = new FileOutputStream(targetPath);
// 輸出
out.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.3測試示例
@Test
public void test(){
try {
// 文件路徑
String filePath = "C:\\mydata\\generator\\世界地圖.png";
// 編碼
String encodeBase64File = encodeBase64File(filePath);
// 剔除base64聲明頭
String code = encodeBase64File.replace("data:image/png;base64,", "");
//解碼
decodeBase64File(code,"C:\\mydata\\generator\\base64.png");
} catch (Exception e) {
e.printStackTrace();
}
}