Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

closing nested streams [duplicate]

Possible Duplicate:
Best way to close nested streams in Java?

How we close nested streams? Closing all of them? If yes what is the order?

FileOutputStream out = new FileOutputStream("data.txt", true);
PrintWriter pout = new PrintWriter(out);

/* do some I/O */

pout.close();
out.close();

or closing the the out most stream will close all of them.

pout.close(); // Is this enough?
like image 930
Majid Azimi Avatar asked Dec 22 '22 11:12

Majid Azimi


2 Answers

When closing chained streams, you only need to close the outermost stream. Any errors will be propagated up the chain and be caught.

Take a look at here. Probably this question has been asked before.

like image 61
MD Sayem Ahmed Avatar answered Dec 24 '22 02:12

MD Sayem Ahmed


Always close resources with a finally block:

acquire();
try {
    use();
} finally {
    release();
}

Your only resource here is the FileOutputStream, so it's the only one which really needs to be closed. If the PrintWriter constructor was to throw, you really should release the FileOutputStream anyway, which precludes just closing the PrintWriter.

Note, you really do want to flush the PrintWriter. This only needs to be done in the non-exception case so doesn't need a finally.

like image 44
Tom Hawtin - tackline Avatar answered Dec 24 '22 01:12

Tom Hawtin - tackline