Java 文件和byte数组转换
2015-10-26 15:49
423 查看
直接上代码
/** * 获得指定文件的byte数组 */ private byte[] getBytes(String filePath){ byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } /** * 根据byte数组,生成文件 */ public static void getFile(byte[] bfile, String filePath,String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在 dir.mkdirs(); } file = new File(filePath+"\\"+fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bfile); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }
相关文章推荐
- Spring中配置数据源的4种形式
- Java Web指导方向
- java反射
- JAVA Calendar的求一个月的最后一天多种方法实现
- 【Java】JavaEE性能问题的10大诱因
- Eclipse常用快捷键使用
- 学习MyBatis与Spring,Maven报错整理!
- spring 主题使用详解
- java实现正则表达式
- 关于spring的启动配置
- java计算百分比,取小数点后两位
- Java:按值传递还是按引用传递详细解说
- 【Java】Java 性能调优指南 – 高性能Java
- Spring事务处理,以及Spring事务的传播属性和隔离级别
- Java反射机制
- Java实现两个矩阵相乘
- Java笔记集合之HashMap
- Java 字符终端上获取输入 System.in
- spring事务管理
- Spring对Hibernate事务管理