Search code examples
javabufferedreader

BufferedReader is closed when returned from method


I'm writing code to read a file and process it and I'm splitting logic into many small methods. So I have a method to read the file and return BufferedReader and another one to do logic with the returned BufferedReader object. But when I try to read lines from the BufferedReader object in the second method it gives me [java.io.IOException: Stream Closed].

The method I used to read the file and return BufferedReader

private static BufferedReader readFile(String file) {
    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        System.out.println(bufferedReader.readLine()); // this line is working successfully
        return bufferedReader;
    } catch (FileNotFoundException fileNotFoundException) {
        fileNotFoundException.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Any idea why the happens and how to solve it ?


Solution

  • You are using try-with-resources:

    try (FileInputStream fileInputStream = new FileInputStream(file)) {
    

    This line is creating a FileInputStream which can be used inside your try block. As soon as you leave your try block, the close() method will be called onto the stream. So if you return the stream or its BufferedReader, the stream will already be closed. You should not use try-with-resources or even better, return whatever you need from the stream instead of the stream itself.