我有这个 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(),有没有更好的方法来做到这一点?我试图将输出流置于循环之外,但它不起作用。
最佳答案
使用缓冲流会产生巨大差异。
试试这个:
for(final File file : files) {
final InputStream in = new BufferedInputStream(new FileInputStream(file));
final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(...)));
try {
// Process each file and save it to file
}
finally {
try {
in.close();
}
catch (IOException ignored) {}
try {
out.close();
}
catch (IOException ignored) {}
}
}
请注意,关闭流时可能抛出的 IOException
必须被忽略,否则您将丢失潜在的初始异常。
另一个问题是两个流都在同一个文件上,这是行不通的。所以我想您正在使用两个不同的文件。
关于java - 输入流和输出流读取文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792779/