输入流和输出流读取文件列表
我有这个 ArrayList 文件,
for(File file : files){
InputStream in = FileInputStream(file);
// process each file and save it to file
OutputStream out = FileOutputStream(file);
try{
} finally {
in.close();
out.close();
}
}
性能非常慢,因为每个循环都有一个 in/out close(),有没有更好的方法来做到这一点?我试图将输出流置于循环之外,但它不起作用。
I have this ArrayList files
for(File file : files){
InputStream in = FileInputStream(file);
// process each file and save it to file
OutputStream out = FileOutputStream(file);
try{
} finally {
in.close();
out.close();
}
}
the performance is really slow since every loop there is a in/out close(), is there a better way to do this? I tried to put outputstream oustide of the loop, it doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用缓冲流会产生巨大的差异。
试试这个:
请注意,关闭流时可能抛出的 IOException 必须被忽略,否则您将丢失潜在的初始异常。
另一个问题是两个流都在同一个文件上,这是行不通的。所以我想你正在使用两个不同的文件。
Using buffered streams makes a huge difference.
Try this:
Note that the
IOException
s that can be thrown when closing the streams must be ignored, or you will lose the potential initial exception.Another problem is that both streams are on the same file, which doesn't work. So I suppose you're using two different files.
close() 最多可能需要 20 毫秒。我怀疑这是你的程序,除非你有 1000 个文件。
我怀疑你的性能问题是缺乏缓冲输入和输出。你能展示一下你的缓冲包装吗?
A close() can take up to 20 ms. I doubt this is your program unless you have 1000's of files.
I suspect your performance problem is a lack of buffering the input and output. Can you show your buffering wrappers as well?
当然,您可以构建一个 OutputStreams 队列并将其卸载到处理这些输出流关闭的后台线程。对于输入流也是如此。
或者,您可以将其留给 JVM 来完成此操作 - 只需不要关闭文件,而将其留给 GC 在对象完成时完成此操作。
you can of course build a queue of OutputStreams and offload that to a background thread that handles the closing of these outputstreams. Same for InputStreams.
Alternatively you can leave it down to the JVM to do that -- simply don't close the files and leave it to the GC to do that when objects are finalized.