2012-06-28 39 views
2

我正在使用Apache Commons FileUpload庫來上傳文件。我想將InputStream的內容複製到單個字節數組中。我怎麼能這樣做?如何將輸入流的內容複製或存儲到字節數組中?

try { 
    List<FileItem> items = new ServletFileUpload(
      new DiskFileItemFactory()).parseRequest(request); 
    for (FileItem item : items) { 
     if (item.isFormField()) { 
      // Process regular form field (input 
      // type="text|radio|checkbox|etc", select, etc). 
      String fieldname = item.getFieldName(); 
      String fieldvalue = item.getString(); 
      out.println("returned"); 
     } else { 
      // Process form file field (input type="file"). 
      String fieldname = item.getFieldName(); 
      String filename = FilenameUtils.getName(item.getName()); 
      InputStream input = item.getInputStream(); 
      if (fieldname.equals("file")) { 
       // please help me here. 
       byte[] allbyte = ??? 
      } 
     } 
    } 
} 
+2

你試過['InputStream.read'](http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte [],%20int,% 20int))? –

回答

0

如何使用ByteArrayOutputStream

ByteArrayOutputStream out = new ByteArrayOutputStream(); 

int b = input.read(); 
while (b != -1) { 
    out.write(b); 
    b = input.read(); 
} 
allbyte = out.toByteArray(); 
+2

應該注意,'ByteArrayOutputStream.toByteArray()'分配一個新數組,並將字節複製到它。換句話說,您不只是首先獲得用於收集數據的數組的參考。如果你處理的文件非常大,而且雙倍複製字節的成本變高,這可能是相關的。 –

-1

使用DataInputStream。它有一個讀取所有字節的readFully()方法。

DataInputStream dis = new DataInputStream(inputStream); 
byte[] allBytes = new byte[inputStream.available()]; 
dis.readFully(allBytes); 

有關詳細信息,請參閱

InputStream

DataInputStream

+3

我不確定您可以依靠'inputStream.available()'來爲您提供上傳數據大小的真實表示。可用返回*「估計可以從此輸入流讀取(或跳過)的字節數,而不會被下一個調用者對此輸入流的方法阻塞。」* –

+0

@GregKopff inputStream.available()返回程序中可以讀取的字節數。這不是問題,因爲分配多餘的長度沒有用,因爲我們只能讀取其中的一部分,而另一個將是空的,這隻會浪費內存 –

2

使用IOUtils.toByteArray()工具方法從Apache commons-io庫:

import org.apache.commons.io.IOUtils; 

InputStream input; 
byte[] bytes = IOUtils.toByteArray(input); 

它給你一個班輪。一般來說,試圖找到一個你想要的現有庫,並且Apache commons libraries有許多方便的方法。

+0

應該注意的是,像JDK版本一樣,Apache Commons的ByteArrayOutputStream .toByteArray()'分配一個新數組,並將字節複製到它。換句話說,您不只是首先獲得用於收集數據的數組的參考。如果你處理的文件非常大,而且雙倍複製字節的成本變高,這可能是相關的。 –

+0

如果我們有一個'InputStream'(一個圖像)並且想要在其上執行一些方法(不將它保存在服務器上),將它寫入一個字節數組並將其傳遞給方法而不是傳遞它作爲'InputStream'? – theyuv

相關問題