1

We have a linux app where we are not able to unmount a USB drive because of the below call. Is there a file resource I need to properly close the stream?

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

here is the output from the response:

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).)

we are currently using java 8.

simgineer
  • 1,754
  • 2
  • 22
  • 49

1 Answers1

2

You need to close the directory stream that you open:

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));
    }

Another way is calling paths.close() directly.

Joni
  • 108,737
  • 14
  • 143
  • 193