• Post Reply Bookmark Topic Watch Topic
  • New Topic

Do we need to close FileWriter Object???  RSS feed

 
Balaji Sampath
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers
For the following code below do we need to close the filewriter object in finally block even when i close BufferedWriter Object.


private void appendFile(String fileName) throws IOException{
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName, true));
String textToFile= "Hello";
bw.write(textToFile);
bw.newLine();
bw.flush();
} catch (IOException ioe) {
throw ioe;

} finally { // close the file
if (bw != null)try {
bw.close();

} catch (IOException ioe2) {
throw ioe2;
}
} // end try/catch/finally





}
Suppose you call this method from say a class giving fileName has the input parameter the programs works fine but Occasionally it says Input file opened lot of resources .
So was not sure if i do need to close the filewriter instance opened..
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you do not need to close the underlying FileWriter.

The Javadoc documentation of BufferedWriter unfortunately doesn't say anything about this (it should have mentioned that it closes the underlying writer, but it doesn't). So I looked in the source code for class BufferedWriter, which I found in the src.zip in my JDK directory. The source code for the close() method looks like this:

It does close the underlying Writer ("out" in the source code above, which is a member variable of class BufferedWriter).

So if you have a problem with too many resources opened, this is not the cause of it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!