2013-12-20 41 views
0

我有一個文件,它由一個寫入文件開頭的序列化String對象組成,後面跟着我試圖提取的文件的原始字節。使用BufferedOutputStream創建大文件需要很長時間

這裏是我的代碼:

FileInputStream fileInputStream = new FileInputStream("C:\Test.tst"); 
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
String string = (String) objectInputStream.readObject(); 
FileOutputStream fileOutputStream = new FileOutputStream("C:\ExtractedTest.tst"); 
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); 
while(fileInputStream.available()) 
{ 
    int i = fileInputStream.read(); 
    bufferedOutputStream.write(i); 
} 
bufferedOutputStream.close(); 
fileOutputStream.close(); 

的代碼將不可用很長一段時間對於大文件(1.5 GB,例如)。我如何加快代碼?我使用錯誤的類嗎?

問候。

+0

定義'不可用的長time' - 你期待什麼時候? – reto

+0

與通過'mkfile'創建文件相比,這需要很長時間嗎? –

回答

1

首先,你不需要我猜想:

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 
String string = (String) objectInputStream.readObject(); 

...和你的循環應該看起來更像是:

final byte[] temp = new byte[1000]; 
while (fileInputStream.available() > 0){ 
int i = fileInputStream.read(temp); 
bufferedOutputStream.write(temp, 0, i); 
} 
+0

並記住關於fileInputStream:] – michali

+0

假設文件後面有另一個對象,而第一個對象是代表文件大小的長型對象。是否有可能虹吸出文件? temp [1000]超出文件邊界到第二個對象。 –

+0

@DannyRancher我不明白你在說什麼,但變量i代表你想要寫入輸出流的字節數。也許玩這個或更清楚地解釋你想達到什麼;) – michali

相關問題