博主发表的文章,有的是自己原创,有的是这些年本人从网上积累的,方便大家学习。
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileOutputStream;
- importsun.misc.BASE64Decoder;
- importsun.misc.BASE64Encoder;
- publicclassFileToBase64{
- /**
- *<p>将文件转成base64字符串</p>
- *@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);
- }
- /**
- *<p>将base64字符解码保存文件</p>
- *@parambase64Code
- *@paramtargetPath
- *@throwsException
- */
- publicstaticvoiddecoderBase64File(Stringbase64Code,StringtargetPath)throwsException{
- byte[]buffer=newBASE64Decoder().decodeBuffer(base64Code);
- FileOutputStreamout=newFileOutputStream(targetPath);
- out.write(buffer);
- out.close();
- }
- /**
- *<p>将base64字符保存文本文件</p>
- *@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();
- }
- }
- }
【本文是清一色专栏作者张勇波的原创文章,转载请通过清一色获取作者授权】
©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经