I am trying an example from
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
in the example the BufferReader is not closed is that necessary to close the BufferReaderor not? Please explain.
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
Always close streams. It’s a good habit which helps you to avoid some odd behaviour. Calling
close()method also callsflush()so you don’t have do this manually.The best place where to close streams is probably in a
finallyblock. If you have it like in your example and an exception occurs before thein.close()line, the stream won’t be closed.And if you have chained streams, you can only close the last one and all before it are closed too. This means
br.close()in your example – notin.close();Example
Alternatively you can use closeQuietly(java.io.InputStream) in Apache Commons library.