文件(pdf、ofd、txt)和Base64的互相轉(zhuǎn)化
描述:Base64是一種編碼算法,3字節(jié)擴(kuò)為4字節(jié),長度增加33%
參考鏈接:https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576
1.文件轉(zhuǎn)Base64
/**
* 獲取文件base64
* @param filePath:文件本地磁盤路徑
* @return:base64串
*/
public static String fileToBase64(String filePath){
String base64String=null;
InputStream in = null;
try {
if(StringUtils.isNotEmpty(filePath)){
File file=new File(filePath);
if(file.exists()&&file.isFile()){
in = new FileInputStream(file);
byte[] bytes=new byte[(int)file.length()];
in.read(bytes);
base64String=Base64.encodeBase64String(bytes);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null!=in){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return base64String;
}
2.base64轉(zhuǎn)文件
/**
* 將base64轉(zhuǎn)為文件
* @param base64 文件base64
* @param filePath 文件路徑
*/
public static void base64ToFile(String base64,String filePath) throws Exception {
OutputStream os = null;
try {
if(StringUtils.isEmpty(filePath)){
throw new Exception("文件路徑不能為空");
}
File file=new File(filePath);
if(!file.exists()){
file.createNewFile();
os=new FileOutputStream(file);
byte[] fileBytes = Base64.decodeBase64(base64);
os.write(fileBytes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null != os){
os.close();
}
}
}