(资料图)
博主发表的文章,有的是自己原创,有的是这些年本人从网上积累的,方便大家学习。
[[178773]]
importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;publicclassFileToBase64{/***将文件转成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)throwsException{byte[]buffer=newBASE64Decoder().decodeBuffer(base64Code);FileOutputStreamout=newFileOutputStream(targetPath);out.write(buffer);out.close();}/***将base64字符保存文本文件
*@parambase64Code*@paramtargetPath*@throwsException*/publicstaticvoidtoFile(Stringbase64Code,StringtargetPath)throwsException{byte[]buffer=base64Code.getBytes();FileOutputStreamout=newFileOutputStream(targetPath);out.write(buffer);out.close();}publicstaticvoidmain(String[]args){try{Stringbase64Code=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(Exceptione){e.printStackTrace();}}}
【本文是清一色专栏作者张勇波的原创文章,转载请通过清一色获取作者授权】