Eclipse 说 PrintStream 从未关闭,即使它已关闭

Eclipse says PrintStream never closed even though it is closed

我应该只用 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!");

}

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

您必须始终在 try-finally 块中关闭您的流,或者,如果您使用 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)) {

    ....

}