Should I explain that all threads are closed if they are wrapped in a buffer through java?

private InputStream input; private InputStreamReader inputReader; private BufferedReader reader; try { input = new InputStream(); inputStreamReader = new InputStreamReader(inputStream); reader = new BufferedReader(inputStreamReader); // do I/O operations } catch (IOException e) { Log.d("IOException", "The Data Could Not Be Read =/"); } finally { try { reader.close(); // now will this, by default, close all other streams? OR /* * input.close(); inputStream.close(); //is this necessary, along with * reader.close(); */ } catch (IOException ex) { ex.printStackTrace(); } } 

Today I came across this question and am not sure whether they will be closed, since they are wrapped or it is still necessary to close all threads independently of each other.

+5
source share
3 answers

If any reader or stream decorates another reader / stream, then closing the outside also closes the inside. This can be done from the Javadoc Closeable#close() :

Closes this thread and allocates any associated system resources .

This also applies to core resources.

If you are very curious, you can delve into the sources of these classes, for example. in BufferedReader :

 public void close() throws IOException { synchronized (lock) { if (in == null) return; try { in.close(); } finally { in = null; cb = null; } } } 

where in is the base Reader .

+8
source

Yes, decorated streams are also closed.

 InputStream in = new FileInputStream("c:\\myfile.txt"); InputStreamReader reader = new InputStreamReader(in); BufferedReader bufferedReader = new BufferedReader(reader); bufferedReader.close(); in.read(); // throws an IOException (no such file or directory) reader.read(); // throws an IOException (Stream closed) 
+5
source

From Java 7, you can use a try-with-resource block (and the fact that closing the reader closes the rest)

 try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), "UTF-8"))) { // do I/O operations } catch(IOException e) { Log.d("IOException", "The Data Could Not Be Read =/", e); } 
+4
source

Source: https://habr.com/ru/post/1237360/


All Articles