簡體   English   中英

使用BufferedOutputStream創建大文件需要很長時間

[英]Creating large file with BufferedOutputStream takes a long time

我有一個文件,該文件由一個序列化的String對象組成,該對象寫入文件的開頭,然后是我嘗試提取的文件的原始字節。

這是我的代碼:

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),該代碼花費了無法使用的長時間。 如何加快代碼速度? 我使用了錯誤的課程嗎?

問候。

首先,您不需要我猜:

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);
}

您可以嘗試通過更改緩沖區大小來微調您的應用程序。

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedOutputStream.html

在這里,您記錄了帶有緩沖區大小的構造函數的版本。 也許您可以使用大緩沖區(當然,要以犧牲內存使用為代價,也准備增加堆大小)

增加Java中的堆大小

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM