JAVA中文件与Byte数组相互转换的方法
JAVA中文件与Byte数组相互转换的方法,如下:
1 public class FileUtil { 2 3 //将文件转换成Byte数组 4 public static byte[] getBytesByFile(String pathStr) { 5 File file = new File(pathStr); 6 try { 7 FileInputStream fis = new FileInputStream(file); 8 ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); 9 byte[] b = new byte[1000]; 10 int n; 11 while ((n = fis.read(b)) != -1) { 12 bos.write(b, 0, n); 13 } 14 fis.close(); 15 byte[] data = bos.toByteArray(); 16 bos.close(); 17 return data; 18 } catch (Exception e) { 19 e.printStackTrace(); 20 } 21 return null; 22 } 23 24 //将Byte数组转换成文件 25 public static void getFileByBytes(byte[] bytes, String filePath, String fileName) { 26 BufferedOutputStream bos = null; 27 FileOutputStream fos = null; 28 File file = null; 29 try { 30 File dir = new File(filePath); 31 if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在 32 dir.mkdirs(); 33 } 34 file = new File(filePath + "\\" + fileName); 35 fos = new FileOutputStream(file); 36 bos = new BufferedOutputStream(fos); 37 bos.write(bytes); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } finally { 41 if (bos != null) { 42 try { 43 bos.close(); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 if (fos != null) { 49 try { 50 fos.close(); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 } 56 } 57 }
本文来自博客园,作者:PC君,转载请注明原文链接:https://www.cnblogs.com/pcheng/p/6913535.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)