wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes close() method; I/O class chaining Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "close() method; I/O class chaining" Watch "close() method; I/O class chaining" New topic
Author

close() method; I/O class chaining

Ram Manoj
Ranch Hand

Joined: Jan 12, 2008
Posts: 52
From K&B book
Whenever you're done using a file, either reading it or writing
to it, you should invoke the close() method.


But when using chaining with I/O classes is invoking the close() method on the Top wrapped class like PrintWriter or BufferedReader sufficient.
How does the mechanism of close() work when chaining?

Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1280

Hi Ram,

in your example you have a PrintWriter wrapping a BufferedWriter wrapping a FileWriter.

Because of this it's sufficient to call close() on the outermost I/O object (PrintWriter) and this one will call close() on the writer it has wrapped which in turn will call close() on the writer it has wrapped and so on until the end of the chain (the innermost writer = FileWriter).

Marco
Ram Manoj
Ranch Hand

Joined: Jan 12, 2008
Posts: 52
Thanks Mark.

This's been a long lasting doubt for me.

Can you point to a link related to this.
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1280

Unfortunately I don't find a really good link at the moment which explains the chaining of Java I/O classes.

Perhaps this Wikipedia article about the decorator pattern may enlighten you. It doesn't describe the Java I/O classes at all, but it's effectively the decorator design pattern which is used when wrapping one object with another as in the case with the Java I/O classes. This and related links hopefully may help you to better understand the concept behind this.

Marco
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: close() method; I/O class chaining
 
Similar Threads
File IO - BufferedWriter/FileWriter
FileIO
how to see how control is moving in a java program during execution
Can not find my error ? Help
Create .txt file