1

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?

Patrick
  • 264
  • 2
  • 8

4 Answers4

2

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.

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 1
    You're right. The problem does not occur, if I run just the code I posted. Though it threw the exception because there were just no more files left to open. Seems I have to find the leak somewhere else. – Patrick Nov 10 '10 at 10:14
1

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.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
  • The stack trace points only to the code, I posted. But you're right the problems is somewhere else. – Patrick Nov 10 '10 at 10:17
1

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

Community
  • 1
  • 1
posdef
  • 6,498
  • 11
  • 46
  • 94
0

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();
}
khachik
  • 28,112
  • 9
  • 59
  • 94