Patrick
Patrick

Reputation: 314

java.io.FileNotFoundException (Too many open files)

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?

Upvotes: 1

Views: 7093

Answers (4)

dogbane
dogbane

Reputation: 274612

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.

Upvotes: 2

khachik
khachik

Reputation: 28693

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();
}

Upvotes: 0

posdef
posdef

Reputation: 6532

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

Upvotes: 1

Adeel Ansari
Adeel Ansari

Reputation: 39907

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.

Upvotes: 1

Related Questions