Java中文件与字节数组转换

本文介绍了如何将文件转化为字节数组及如何将字节数组保存为文件的实现方法,包括代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


[c-sharp]  view plain copy
  1. /** 
  2.      * 文件转化为字节数组 
  3.      *  
  4.      * @param file 
  5.      * @return 
  6.      */  
  7.     public static byte[] getBytesFromFile(File file) {  
  8.         byte[] ret = null;  
  9.         try {  
  10.             if (file == null) {  
  11.                 // log.error("helper:the file is null!");  
  12.                 return null;  
  13.             }  
  14.             FileInputStream in = new FileInputStream(file);  
  15.             ByteArrayOutputStream out = new ByteArrayOutputStream(4096);  
  16.             byte[] b = new byte[4096];  
  17.             int n;  
  18.             while ((n = in.read(b)) != -1) {  
  19.                 out.write(b, 0, n);  
  20.             }  
  21.             in.close();  
  22.             out.close();  
  23.             ret = out.toByteArray();  
  24.         } catch (IOException e) {  
  25.             // log.error("helper:get bytes from file process error!");  
  26.             e.printStackTrace();  
  27.         }  
  28.         return ret;  
  29.     }  


[java]  view plain copy
  1. /** 
  2.      * 把字节数组保存为一个文件 
  3.      *  
  4.      * @param b 
  5.      * @param outputFile 
  6.      * @return 
  7.      */  
  8.     public static File getFileFromBytes(byte[] b, String outputFile) {  
  9.         File ret = null;  
  10.         BufferedOutputStream stream = null;  
  11.         try {  
  12.             ret = new File(outputFile);  
  13.             FileOutputStream fstream = new FileOutputStream(ret);  
  14.             stream = new BufferedOutputStream(fstream);  
  15.             stream.write(b);  
  16.         } catch (Exception e) {  
  17.             // log.error("helper:get file from byte process error!");  
  18.             e.printStackTrace();  
  19.         } finally {  
  20.             if (stream != null) {  
  21.                 try {  
  22.                     stream.close();  
  23.                 } catch (IOException e) {  
  24.                     // log.error("helper:get file from byte process error!");  
  25.                     e.printStackTrace();  
  26.                 }  
  27.             }  
  28.         }  
  29.         return ret;  
  30.     }  

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值