base64字符串和文件之间的转换
base64字符和文件之间的转换这边主要会用到spring下的两个方法
- Base64Util.encodeToString(byte[]):将byte字节加密成字符串
- Base64Util.decodeFormString(String):将字符串解密成byte[]
/**
* <p>将文件装换成Base64字符串</p>
*
* @param filePath 文件路径
* @return base64字符串
* @since 0.0.1
*/
public static String fileToBase64Str(String filePath) throws IOException {
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
fileInputStream.close();
return Base64Utils.encodeToString(bytes);
}
/**
* <p>将字符串解密成byte[]</p>
*
* @param base64Str BASE64字符串
* @return byte数组
* @since 0.0.1
*/
public static byte[] base64StrToByte(String base64Str) {
return Base64Utils.decodeFromString(base64Str);
}
/**
* <p>将base64文件装换成文件</p>
*
* @param base64Str 加密后的base64文件
* @param filePath 文件路径
* @return boolean true:转换成功,false:转换失败
* @since 0.0.1
*/
public static Boolean base64StrToFile(String base64Str, String filePath) throws IOException {
byte[] bytes = base64StrToByte(base64Str);
FileOutputStream fileInputStream = new FileOutputStream(filePath);
fileInputStream.write(bytes);
fileInputStream.close();
File file = new File(filePath);
return file.exists();
}
public static void main(String[] args) throws IOException {
String base64Str=fileToBase64Str("E:/test/test.png");
Boolean isSuccess=base64StrToFile(base64Str,"E:/test/test1.png");
System.out.println(isSuccess?"成功":"失败");
}