我正在尝试一个例子
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
在示例中,BufferReader是否未关闭,是否需要关闭BufferReader?请解释。

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();

最佳答案

始终关闭流。这是一个好习惯,可以帮助您避免一些奇怪的行为。调用close()方法也会调用flush(),因此您无需手动执行此操作。

关闭流的最佳位置可能是在finally块中。如果像您的示例中那样,并且在in.close()行之前发生异常,则该流将不会关闭。

而且,如果您已链接流,则只能关闭最后一个流,也要关闭所有流。在您的示例中,这表示br.close()而不是in.close()



try {
    // do something with streams
} catch (IOException e) {
    // process exception - log, wrap into your runtime, whatever you want to...
} finally {
    try {
        stream.close();
    } catch (IOException e) {
        // error - log it at least
    }
}


另外,您可以在Apache Commons库中使用closeQuietly(java.io.InputStream)

10-07 13:21
查看更多