问题
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