在數據傳輸過程中經常會遇到將文件轉爲base64編碼然後再進行傳輸,接收方接收到編碼數據後,需要進行解碼,獲取到文件。
JDK 1.8 以後,util 包下自帶 Base64 相關工具類,直接拿來使用能很快的解決我們的問題。
利用JDK 自帶的 Base 相關工具,寫一個如下的工具類來處理 base64 編碼與文件的轉換:
public class Base64Utils {
/**
* 將文件進行base64編碼
*
* @param filePath 文件路徑
* @return 文件編碼後的字符串
*/
public static String encode (String filePath) throws Exception {
FileInputStream inputStream = new FileInputStream(filePath);
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
return Base64.getEncoder().encodeToString(data);
}
/**
* 將文件base64編碼轉爲文件
*
* @param base64 文件base64編碼
* @param filePath 文件要保存的路徑
*/
public static void decode(String base64, String filePath) throws Exception {
byte[] data = Base64.getDecoder().decode(base64);
FileOutputStream outputStream = new FileOutputStream(filePath);
outputStream.write(data);
}
}
注:以上代碼只是爲了演示編碼與文件之間轉換的核心操作,未對異常和流對象進行正確的操作,在實際應用中要注意記錄日誌以及合理關閉流對象。
使用 NIO 包下的 Files 和 Paths 工具讀取文件,代替 FileInputStream:
public class Base64Utils {
/**
* 將文件進行base64編碼
*
* @param filePath 文件路徑
* @return 文件編碼後的字符串
*/
public static String encode (String filePath) throws Exception {
byte[] data = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(data);
}
/**
* 將文件base64編碼轉爲文件
*
* @param base64 文件base64編碼
* @param filePath 文件要保存的路徑
*/
public static void decode(String base64, String filePath) throws Exception {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
}
}
此方法可以比傳統 IO 包下讀取文件要方便快捷很多,省去了對流的操作。
Files.write(): 將文件寫入指定的位置,第三個參數是表示處理文件的方式,StandardOpenOption.CREATE 如果文件不存在則創建。