importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;public classFileToBase64 {/***
将文件转成base64 字符串
*@parampath 文件路径
*@return*@throwsException*/
public static String encodeBase64File(String path) throwsException {
File file= newFile(path);
FileInputStream inputFile= newFileInputStream(file);byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();return newBASE64Encoder().encode(buffer);
}/***
将base64字符解码保存文件
*@parambase64Code
*@paramtargetPath
*@throwsException*/
public static void decoderBase64File(String base64Code,String targetPath) throwsException {byte[] buffer = newBASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out= newFileOutputStream(targetPath);
out.write(buffer);
out.close();
}/***
将base64字符保存文本文件
*@parambase64Code
*@paramtargetPath
*@throwsException*/
public static void toFile(String base64Code,String targetPath) throwsException {byte[] buffer =base64Code.getBytes();
FileOutputStream out= newFileOutputStream(targetPath);
out.write(buffer);
out.close();
}public static voidmain(String[] args) {try{
String base64Code=encodeBase64File("/Users/Crazy/Pictures/zyb2.jpg");
System.out.println(base64Code);
decoderBase64File(base64Code,"/Users/Crazy/Desktop/zyb.png");
toFile(base64Code,"/Users/Crazy/Desktop/zyb.txt");
}catch(Exception e) {
e.printStackTrace();
}
}
}