Java实现文件和base64流的相互转换功能示例
本文实例讲述了Java实现文件和base64流的相互转换功能。分享给大家供大家参考,具体如下:
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
/**
*文件与base64的互相转换操作
*/
publicclasstestFile{
publicstaticvoidmain(String[]args){
testFilet=newtestFile();
try{
Stringret=t.encodeBase64File("d://IE和火狐js或css差异.docx");
System.err.println(ret);
t.decoderBase64File(ret,"d://ghsTest/retFile.docx","d://ghsTest/");
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
/**
*将文件转成base64字符串
*
*@parampath文件路径
*@return*
*@throwsException
*/
publicstaticStringencodeBase64File(Stringpath)throwsException{
Filefile=newFile(path);
FileInputStreaminputFile=newFileInputStream(file);
byte[]buffer=newbyte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
returnnewBASE64Encoder().encode(buffer);
}
/**
*将base64字符解码保存文件
*
*@parambase64Code
*@paramtargetPath
*@throwsException
*/
publicstaticvoiddecoderBase64File(Stringbase64Code,StringtargetPath,Stringcatalogue)
throwsException{
Filefile=newFile(catalogue);
if(file.exists()==false){
file.mkdirs();
}
byte[]buffer=newBASE64Decoder().decodeBuffer(base64Code);
FileOutputStreamout=newFileOutputStream(targetPath);
out.write(buffer);
out.close();
}
}
PS:这里再推荐几款加密解密相关在线工具供大家参考使用:
线编码转换工具(utf-8/utf-32/Punycode/
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短