Java中文件与字节数组转换

注:来源于JavaEye

文件转化为字节数组:

http://www.javaeye.com/topic/304980

[c-sharp] view plaincopy
  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.     }  

字节数组转化为文件

http://www.javaeye.com/topic/304982

  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.     } 
原文地址:https://www.cnblogs.com/langtianya/p/3968972.html