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.
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: