java.io.FileNotFoundException (Too many open files)

时光怂恿深爱的人放手 提交于 2020-01-06 02:40:07

问题


I use the following code to write some data to files:

BufferedWriter writer = null;
try {
    writer = new BufferedWriter(new FileWriter(file));
    writer.write(...);
    writer.flush();
}
finally {
    if (writer != null)
        writer.close();
}

After invoking the method multiple times I got a FileNotFoundException because too many files are open.

Obviously java does not close the file handles when I close the writer stream. Closing the FileWriter separately does not help.

Is there sth. I can do to force java to close the files?


回答1:


Your code looks fine. It could be another part of your application which is leaking file handles.

You can monitor file handles using lsof on Linux or pfiles on Solaris. On Windows, you can use ProcessExplorer.




回答2:


No, Java does close the file handles when you close the writer. Its actually built using Decorator pattern. Hence, it must be something else. Show the stack trace.




回答3:


See this thread about writing to files, good tips there.. pay attention to the finally block in Anons reply.




回答4:


BufferedWriter closes the underlying stream. Probably, this a multithreading issue. You can keep an instance of FileOutputStream and close it. Something like:

java.io.FileOutputStream out = new java.io.FileOutputStream(file);
try {
  // make buffered writer, etc.
} finally {
  out.close();
}


来源:https://stackoverflow.com/questions/4095347/java-io-filenotfoundexception-too-many-open-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!