File Reading in Java, with same file readers

119 Views Asked by At

I have two files to be read using same variables for the task with the following code:

    try {
            FileInputStream fis = new FileInputStream(filename1);
            InputStreamReader isr = new InputStreamReader(fis, "UTF8");
            BufferedReader br = new BufferedReader(isr);
            String line="";
            while((line=br.readLine())!=null){
            System.out.println(line);
            }

            // Do i need to add these 3 statements ...
            //br.close();
            //isr.close();
            //fis.close();
            //Without the above 3 statements also the code works fine ...

            fis = new FileInputStream(filename2);
            isr = new InputStreamReader(fis, "UTF8");
            br = new BufferedReader(isr);
            line="";

            while((line=br.readLine())!=null){
            System.out.println(line);
            }

            br.close();
            isr.close();
            fis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

The filereading in java doesn't bother about closing the opened stream and releasing any system resources associated with it for the first file filename1?

No exceptions thrown.

3

There are 3 best solutions below

0
On

The code works, but it is not a good practice.

Java will automatically close the first file when the garbage collector decides to run and to deallocate your first FileInputStream object. This might happen at any time after you lose the last reference to the object, but might even not happen at all, depending on your memory conditions.

If you are using Java 7, you can use the try with resources construct, which will call close for you:

try (FileInputStream fis = new FileInputStream(filename1);
     InputStreamReader isr = new InputStreamReader(fis, "UTF8");
     BufferedReader br = new BufferedReader(isr)) {
    // Code...
}
0
On

So you have a resource leak which won't cause a problem for you unless you;

  • attempt to delete the file on Windows (as the file is still open)
  • do this many times in which case you might run out of file handles.
0
On

Once you created new instance for the StreamReader, Automatically call the garbage collection for the previously opened stream.