为什么使用 String 初始化的 InputStream 在 try-with-resources 之外保持打开状态?

Why does an InputStream initialized with a String stay open outside a try-with-resources?

我注意到由于流被自动关闭,这会按预期抛出 IOException

BufferedReader bufferedReader;

try (FileReader fileReader = new FileReader(new File("pom.xml"))) {
    bufferedReader = new BufferedReader(fileReader);
}

bufferedReader.readLine();

而当 InputStream 使用 String 初始化时,它不会:

BufferedInputStream bufferedInputStream;

try (InputStream inputStream = IOUtils.toInputStream("test")) {
    bufferedInputStream = new BufferedInputStream(inputStream);
}

bufferedInputStream.read();

BufferedReaderBufferedInputStream 都是用括号外闭合的对象初始化的。它与 InputStream 在内部处理 String 的方式有关吗?

你误会了什么。

唯一自动关闭的资源是初始括号内的资源:

try (
    final R r1 = ...;
) {
    final R r2 = ...;
} // at this point, r1 is closed for you; r2 is NOT

请注意,您也可以在初始括号中声明多个资源。

除了, the InputStream returned by IOUtils#toInputStream("test") is a ByteArrayInputStream whose close方法是一个空操作。

Closing a ByteArrayInputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

FileReader 内部维护文件句柄。一旦您在 FileReader 上调用 close 并且包装 BufferedReader 将无法使用它,该句柄就会变得无效。 ByteArrayInputStream.

不会发生这种情况