【问题标题】:Eclipse says PrintStream never closed even though it is closedEclipse 说 PrintStream 从未关闭,即使它已关闭
【发布时间】:2018-08-19 20:04:25
【问题描述】:

我应该只使用 try/catch/finally 块关闭 PrintStream 还是有其他方法?

或者这是 IDE 中的错误?

public void writeData(String fileDir) throws IOException{

    FileOutputStream fos = new FileOutputStream(fileDir);
    PrintStream ps = new PrintStream(fos);

    for(int i = 0; i < 3; i++) {
        ps.print(stringData[i]);
        ps.print("-");
        ps.print(doubleData[i]);
        ps.print("-");
        ps.print(intData[i]);
        ps.println();

        boolean control = ps.checkError();
        if(control) {
            throw new IOException("IO exception occurred!");
        }
    }

    ps.close();

    System.out.println("Data transfer completed!");

}

【问题讨论】:

  • 使用try with resources。此代码不保证关闭流。
  • 您的代码在至少一个代码路径上抛出IOException。如果没有try-finally(或try-with-resources),您会将fos 后面的文件句柄打开。

标签: java resource-leak printstream


【解决方案1】:

如果控制变量为真,则会抛出 IOException,因此,在这种情况下,您永远不会关闭您的 PrintStream。

您必须始终在 try-finally 块中关闭您的 Streams,或者,如果您使用 java 1.7,则在 try-with-resources 中。

另外,你也忘记关闭FileOutputStream了。

试一试

try {
    FileOutputStream fos = new FileOutputStream(fileDir);
    PrintStream ps = new PrintStream(fos);

    ...

} finally {
     fos.close();
     ps.close();
}

资源尝试

try (FileOutputStream fos = new FileOutputStream(fileDir); PrintStream ps = new PrintStream(fos)) {

    ....

}

【讨论】:

  • 这里不需要关闭FileOutputStreamPrintStream 获得所有权并在PrintStream 关闭时关闭FileOutputStream。 (同样适用于Scanner,如果使用它构造它,它会关闭System.in - 经常导致其他错误。)
猜你喜欢
  • 1970-01-01
  • 2016-01-14
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 2016-04-07
  • 1970-01-01
  • 2015-05-31
相关资源
最近更新 更多