Base64与文件流之间的相互转换
文件流转换成Base64
/** * 文件流转换成Base4 */ public String fileToBase64(String path){ String base64 = null; InputStream in = null; try { File file = new File(path); in = new FileInputStream(file); byte[] bytes=new byte[(int)file.length()]; in.read(bytes); base64 = Base64.getEncoder().encodeToString(bytes); } catch (Exception e) { e.printStackTrace(); }finally { if(in!=null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; }
Base64转换成文件流
/** * Base64解码成File文件 */ public static void base64ToFile(String base64,String fileName){ File file = null; //创建文件目录 String filePath = "C:\\Users\\hemanman6\\Desktop"; File dir = new File(filePath); if(!dir.exists()&& !dir.isDirectory()){ dir.mkdirs(); } BufferedOutputStream bos = null; FileOutputStream fos = null; byte[] bytes = Base64.getDecoder().decode(base64); file = new File(filePath+"\\"+fileName); try { fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally{ if(bos!=null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos!=null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
转自:https://blog.csdn.net/qq_38530648/article/details/121562484
分类:
io
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了