Search code examples
javafile-ioiostream

Java IO, are these resources automatically closed?


In this code I read a text file, when BufferedReader is closed by "try-resource" block so the InputStreamReader does, then can I guarantee all the resources are closed like this?

try(final BufferedReader br = new BufferedReader(new InputStreamReader(new 
    FileInputStream(file), charset))) {
        String line = null;

        while((line = br.readLine()) != null) {
            builder.append(line);

        }

    }

In this other example, I write a text file, as is written, are all the resources closed in the end? Is it mandatory to call flush()?

try(final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new 
    FileOutputStream(file), charset))) {
        bw.write(text);
        bw.flush();

    }

Solution

  • Yes, the outermost streams call their inner streams' close() methods, so you only need to call the outermost stream.

    You don't need to call flush(), the streams will flush when necessary and before being closed. Remove that and the code will look perfect.