有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java方法可能无法在异常时关闭流

我发现findbugs出现了一个严重错误:

The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.

try {
...
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...
} catch (IOException e) {
    throw new RuntimeException(e);
} finally {
    try {
        if (stdError != null) {
            stdError.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

我是否还需要关闭InputStreamReaderp.getErrorStream(它返回InputStream


共 (2) 个答案

  1. # 1 楼答案

    当创建BufferedReader对象时引发异常时会发生什么?由InputStreamReader对象管理的流直到垃圾收集器决定销毁该对象时才会关闭

    如果在创建InputStreamReader对象时引发异常,则可能会出现类似问题

  2. # 2 楼答案

    BufferedReader和InputStreamReader在关闭时都会关闭底层流。关闭stdError应该没问题