关闭缓冲读取器是强制性的

Ram*_*esh 0 java

我试图从 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();
Run Code Online (Sandbox Code Playgroud)

use*_*882 8

总是关闭溪流.这是一个很好的习惯,可以帮助你避免一些奇怪的行为.调用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
    } 
}
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*n C 5

从资源泄漏防护的角度来看,如果您还关闭了它包装的流,则不必严格关闭包装流.但是,关闭包装的流可能会导致内容丢失(特别是在输出情况下),因此最好关闭(仅仅)包装器,并依赖于记录的行为,即关闭包装器也会关闭包装的流.(对于标准I/O包装类来说,这确实是正确的!)


像亚历山大一样,我质疑依靠"玫瑰印度"例子的智慧.例如,这个有两个更明显的错误,没有一个不错的Java程序员应该做的:

  • 流未在finally块中关闭.如果在打开和关闭之间抛出任何异常,in.close()则不会执行该语句,并且应用程序将泄漏打开的文件描述符.经常这样做,你的应用程序将开始抛出意想不到的IOExceptions.

  • 链中的DataInputStream没有用处.相反,它们应该fstream用作参数InputStreamReader.或者更好的是,使用FileReader.


最后,这是示例的更正版本:

BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"));
try {
    String line;
    while ((line = br.readLine()) != null)   {
        // Print the content on the console
        System.out.println(line);
    }
} finally {
    // Close the reader stack.
    br.close();
}
Run Code Online (Sandbox Code Playgroud)

或者使用Java 7的"try with resource":

try (BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"))) {
    String line;
    while ((line = br.readLine()) != null)   {
        // Print the content on the console
        System.out.println(line);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果初始化 BufferedReader 时出现异常怎么办?FileReader 仍将打开。 (2认同)