现在的位置: 首页 > 综合 > 正文

Java 文件和byte数组转换

2013年01月04日 ⁄ 综合 ⁄ 共 2228字 ⁄ 字号 评论关闭
Java代码  收藏代码
  1. public class T3 {  
  2.   
  3.     public static void main(String[] args){  
  4.         String filePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src\\1.docx";  
  5.         String outFilePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src";  
  6.         String outFileName = "2.docx";  
  7.           
  8.         getFile(getBytes(filePath),outFilePath,outFileName);  
  9.     }  
  10.   
  11.     /** 
  12.      * 获得指定文件的byte数组 
  13.      */  
  14.     public static byte[] getBytes(String filePath){  
  15.         byte[] buffer = null;  
  16.         try {  
  17.             File file = new File(filePath);  
  18.             FileInputStream fis = new FileInputStream(file);  
  19.             ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
  20.             byte[] b = new byte[1000];  
  21.             int n;  
  22.             while ((n = fis.read(b)) != -1) {  
  23.                 bos.write(b, 0, n);  
  24.             }  
  25.             fis.close();  
  26.             bos.close();  
  27.             buffer = bos.toByteArray();  
  28.         } catch (FileNotFoundException e) {  
  29.             e.printStackTrace();  
  30.         } catch (IOException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.         return buffer;  
  34.     }  
  35.   
  36.     /** 
  37.      * 根据byte数组,生成文件 
  38.      */  
  39.     public static void getFile(byte[] bfile, String filePath,String fileName) {  
  40.         BufferedOutputStream bos = null;  
  41.         FileOutputStream fos = null;  
  42.         File file = null;  
  43.         try {  
  44.             File dir = new File(filePath);  
  45.             if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
  46.                 dir.mkdirs();  
  47.             }  
  48.             file = new File(filePath+"\\"+fileName);  
  49.             fos = new FileOutputStream(file);  
  50.             bos = new BufferedOutputStream(fos);  
  51.             bos.write(bfile);  
  52.         } catch (Exception e) {  
  53.             e.printStackTrace();  
  54.         } finally {  
  55.             if (bos != null) {  
  56.                 try {  
  57.                     bos.close();  
  58.                 } catch (IOException e1) {  
  59.                     e1.printStackTrace();  
  60.                 }  
  61.             }  
  62.             if (fos != null) {  
  63.                 try {  
  64.                     fos.close();  
  65.                 } catch (IOException e1) {  
  66.                     e1.printStackTrace();  
  67.                 }  
  68.             }  
  69.         }  
  70.     }  
  71. }  

抱歉!评论已关闭.