繁体   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