【问题标题】:closing an buffer reader is compulsory关闭缓冲区阅读器是强制性的
【发布时间】:2012-03-11 16:22:21
【问题描述】:

我正在尝试一个示例 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();

【问题讨论】:

标签: java


【解决方案1】:

从防止资源泄漏的角度来看,如果您还关闭了包装流,则不必关闭包装流。但是,关闭包装的流可能会导致内容丢失(特别是在输出情况下),因此最好关闭(仅)包装器,并依赖于记录的行为,即关闭包装器也会关闭包装的流。 (对于标准 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();
}

或使用 Java 7 的“资源尝试”:

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

【讨论】:

  • 如果在初始化 BufferedReader 时出现异常怎么办? FileReader 仍将打开。
  • 假设您在我的回答中谈论代码,是的。查看 BufferedReader 源代码。但是,对于该构造函数,唯一可能的例外是 OOME。
【解决方案2】:

始终关闭流。这是一个好习惯,可以帮助您避免一些奇怪的行为。调用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)

【讨论】:

    【解决方案3】:

    由于底层流已关闭,因此关闭BufferedReader 并不是绝对必要的,即使以相反的顺序(相对于它们打开的顺序)关闭所有Closeables 是一个好习惯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2015-12-25
      • 2017-07-08
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 2017-11-02
      相关资源
      最近更新 更多