How are Java input streams closed?

In the following code:

DataInputStream in = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); in.close(); 

Do I need to close 2 other threads in addition to closing the top-level thread?

+7
java io stream
source share
4 answers

if you look at the source of the DataInputStream , you will see that it also closes the underlying threads. so you do not need. and this (or should be) true for all types of threads.

+8
source share

I will take this opportunity to respond with the answer that I already made earlier.

Using Project Lombok , you can let Lombok properly close threads for you. Details can be found here .

+3
source share

Karazi is right in suggesting this. In addition, to get an idea and a little more information, the Java IO API is actually implemented using a decorator template. You can check the decorator template on the wiki.

+1
source share

I would put an end to the finally block to ensure that it is properly cleared in the event of an exception.

 public void tryToDoWhatever() throws Exception { DataInputStream in = null; try { in = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); } finally { if (in != null) in.close(); } } 
+1
source share

All Articles