我应该关闭使用 java.nio.file.Files.newInputStream 创建的流吗?

Should I close Streams created with java.nio.file.Files.newInputStream?

在流教程中,没有提到关闭从 Files.newInputStream( path ) 获得的流。只有一些晦涩:

Whether the returned stream is asynchronously closeable and/or interruptible is highly file system provider specific and therefore not specified.

在此上下文中,"asyncronously" 是什么?如果我显式关闭流,或者另一个线程异步关闭流?

您一定要关闭获得的 InputStream,就像所有其他人一样。术语 "asynchronously closeable" 指的是在另一个线程因 I/O 操作而阻塞时关闭流的能力。

来自 InterruptibleChannel 文档:

A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException.

您可以使用新的 try with resources 选项方便地执行此操作。

try(/*initialize resources here*/)
{
}

它们会在 try 块之后自动关闭。根据需要添加捕获。