2012-03-28 65 views
11

我有一個API調用返回一個字節數組。我目前將結果串流到一個字節數組中,然後確保校驗和匹配,然後將ByteArrayOutputStream寫入File。代碼是這樣的,它工作得很好。如何編寫一個潛在的巨大InputStream文件?

String path = "file.txt"; 
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 
    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 
    int len = 0; 
    while ((len = inputStream.read(buffer)) != -1) { 
     byteBuffer.write(buffer, 0, len); 
    } 
    FileOutputStream stream = new FileOutputStream(path); 
    stream.write(byteBuffer.toByteArray()); 

我關心我,從InputStream的結果可能會比Android的堆大小大,我能得到OutOfMemory異常如果整個字節數組是在內存中。將inputStream寫入塊中的最優雅的方式是什麼,這樣字節數組永遠不會超過堆大小?

+0

您建議我的擔憂是無關緊要的嗎? – JoeLallouz 2012-03-28 15:27:07

+1

只消除使用'ByteArrayOutputStream'。 (我讀錯了..我用它呢?) – 2012-03-28 15:27:12

回答

10

我建議去跳過ByteArrayOutputStream並寫入到FileOutputStream中,這似乎爲解決我的顧慮。通過一次快速調整,FileOutputStream由BufferedOutputStream進行裝飾

String path = "file.txt"; 
OutputStream stream = new BufferedOutputStream(new FileOutputStream(path)); 
int bufferSize = 1024; 
byte[] buffer = new byte[bufferSize]; 
int len = 0; 
while ((len = is.read(buffer)) != -1) { 
    stream.write(buffer, 0, len); 
} 
if(stream!=null) 
    stream.close(); 
+0

是不是'File'應該是'FileInputStream'?它沒有定義 – 2016-03-03 08:42:16

+1

使用BufferedOutputStream而不是直接使用FileOutputStream有什麼好處? – Xan 2017-05-16 17:55:21

14

請勿寫信給ByteArrayOutputStream。直接寫入FileOutputStream

String path = "file.txt"; 
FileOutputStream output = new FileOutputStream(path); 
int bufferSize = 1024; 
byte[] buffer = new byte[bufferSize]; 
int len = 0; 
while ((len = inputStream.read(buffer)) != -1) { 
    output.write(buffer, 0, len); 
} 
+0

嗯我想這是有道理的。 – JoeLallouz 2012-03-28 15:28:41

+0

我用這個OutputStream output = new BufferedOutputStream(new FileOutputStream(path));閱讀FileOutputStream文檔後。 – JoeLallouz 2012-03-28 16:12:46

+0

隨時編輯我的答案以反映並接受它。否則,你可以/應該發佈並接受你自己的答案。 – 2012-03-28 16:18:45

相關問題