File和byte[]转换

 

File和byte[]转换


  1. public static byte[] File2byte(String filePath)  
  2.     {  
  3.         byte[] buffer = null;  
  4.         try  
  5.         {  
  6.             File file = new File(filePath);  
  7.             FileInputStream fis = new FileInputStream(file);  
  8.             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  9.             byte[] b = new byte[1024];  
  10.             int n;  
  11.             while ((n = fis.read(b)) != -1)  
  12.             {  
  13.                 bos.write(b, 0, n);  
  14.             }  
  15.             fis.close();  
  16.             bos.close();  
  17.             buffer = bos.toByteArray();  
  18.         }  
  19.         catch (FileNotFoundException e)  
  20.         {  
  21.             e.printStackTrace();  
  22.         }  
  23.         catch (IOException e)  
  24.         {  
  25.             e.printStackTrace();  
  26.         }  
  27.         return buffer;  
  28.     }  
  29.   
  30.     public static void byte2File(byte[] buf, String filePath, String fileName)  
  31.     {  
  32.         BufferedOutputStream bos = null;  
  33.         FileOutputStream fos = null;  
  34.         File file = null;  
  35.         try  
  36.         {  
  37.             File dir = new File(filePath);  
  38.             if (!dir.exists() && dir.isDirectory())  
  39.             {  
  40.                 dir.mkdirs();  
  41.             }  
  42.             file = new File(filePath + File.separator + fileName);  
  43.             fos = new FileOutputStream(file);  
  44.             bos = new BufferedOutputStream(fos);  
  45.             bos.write(buf);  
  46.         }  
  47.         catch (Exception e)  
  48.         {  
  49.             e.printStackTrace();  
  50.         }  
  51.         finally  
  52.         {  
  53.             if (bos != null)  
  54.             {  
  55.                 try  
  56.                 {  
  57.                     bos.close();  
  58.                 }  
  59.                 catch (IOException e)  
  60.                 {  
  61.                     e.printStackTrace();  
  62.                 }  
  63.             }  
  64.             if (fos != null)  
  65.             {  
  66.                 try  
  67.                 {  
  68.                     fos.close();  
  69.                 }  
  70.                 catch (IOException e)  
  71.                 {  
  72.                     e.printStackTrace();  
  73.                 }  
  74.             }  
  75.         }  
  76.     }  
原网址:http://blog.csdn.net/commonslok/article/details/9493531

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值