`

java文件的读写

阅读更多
public File getFileFromBytes(byte[] b, String outputFile){
		BufferedOutputStream stream = null; 
        File file = null; 
        try{ 
            file = new File(outputFile); 
            FileOutputStream fstream = new FileOutputStream(file); 
            stream = new BufferedOutputStream(fstream); 
            stream.write(b); 
        } catch (Exception e){ 
            e.printStackTrace(); 
        } finally{ 
            if (stream != null){ 
                try{ 
                    stream.close(); 
                } catch (IOException e1){ 
                    e1.printStackTrace(); 
                } 
            } 
        } 
        return file; 

	}

 

Java代码 复制代码
  1. public static ByteArrayOutputStream readFile(String filename) {   
  2.     try {   
  3.         FileInputStream fileInStream = new FileInputStream(filename);   
  4.         ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();   
  5.         int i = 0;   
  6.         while ((i = fileInStream.read()) != -1) {   
  7.             fileByteStream.write(i);   
  8.         }   
  9.         fileInStream.close();   
  10.         return fileByteStream;   
  11.     } catch (Exception e) {   
  12.         e.printStackTrace();   
  13.     }   
  14.     return null;   
  15. }   
  16.   
  17. public static void writeFile(String fileName, byte[] data) {   
  18.     try {   
  19.         FileOutputStream fos = new FileOutputStream(fileName);   
  20.         fos.write(data);   
  21.         fos.close();   
  22.     } catch (Exception e) {   
  23.         e.printStackTrace();   
  24.     }   
  25.   
  26. }    
  27. //transfor InputStream to byte   
  28. public static byte[] getBytes(InputStream is) throws Exception {   
  29.     byte[] data = null;   
  30.   
  31.     Collection chunks = new ArrayList();   
  32.     byte[] buffer = new byte[1024 * 1000];   
  33.     int read = -1;   
  34.     int size = 0;   
  35.   
  36.     while ((read = is.read(buffer)) != -1) {   
  37.         if (read > 0) {   
  38.             byte[] chunk = new byte[read];   
  39.             System.arraycopy(buffer, 0, chunk, 0, read);   
  40.             chunks.add(chunk);   
  41.             size += chunk.length;   
  42.         }   
  43.     }   
  44.   
  45.     if (size > 0) {   
  46.         ByteArrayOutputStream bos = null;   
  47.         try {   
  48.             bos = new ByteArrayOutputStream(size);   
  49.             for (Iterator itr = chunks.iterator(); itr.hasNext();) {   
  50.                 byte[] chunk = (byte[]) itr.next();   
  51.                 bos.write(chunk);   
  52.             }   
  53.             data = bos.toByteArray();   
  54.         } finally {   
  55.             if (bos != null) {   
  56.                 bos.close();   
  57.             }   
  58.         }   
  59.     }   
  60.     return data;   
  61. }   

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics