在 java 8 中使用 Files.newDirectoryStream() 时如何关闭文件处理程序

How to close the file handler when using Files.newDirectoryStream() in java 8

我们有一个 linux 应用程序,由于以下调用,我们无法卸载 USB 驱动器。是否有我需要的文件资源来正确关闭流?

     Files.newDirectoryStream(
         Paths.get(importDir), 
         path -> path.toString().endsWith(".ini") && path.toFile().isFile())
            .forEach(path -> importItems.add(path));

这是响应的输出:

umount: /media/flashdrive: target is busy
    (In some cases useful info about processes that
     use the device is found by lsof(8) or fuser(1).)

我们目前正在使用 java 8.

您需要关闭您打开的目录流:

Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed

https://docs.oracle.com/javase/8/docs/api/java/nio/file/DirectoryStream.html

    try (DirectoryStream<Path> paths = Files.newDirectoryStream(
            Paths.get(importDir),
            path -> path.toString().endsWith(".ini") && path.toFile().isFile())) {

        paths.forEach(path -> importItems.add(path));
    }

另一种方法是直接调用 paths.close()