在項目中需要用到文件傳輸入民宿,有時需要將文件轉(zhuǎn)成base64字串稻爬,再將base64字串轉(zhuǎn)成字節(jié)流保存在文件了杜耙。
/**
* 將文件轉(zhuǎn)成base64 字符串
* @param path 文件路徑
* @return
* @throws Exception
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
/**
* 將base64字符解碼保存文件
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* 將base64字符保存文本文件
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void toFile(String base64Code,String targetPath) throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}