1

I'm using Java's DirectoryStream to get a list of all the files/subfolders in a directory. However, after going through all the files and folders of the directory, my code then proceeds to go through all the subdirectories. How can I stop it from going through my sub directories as well?

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry : stream) {
            list.add(entry.getFileName().toString());
            System.out.println(entry.getFileName());
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brandan B
  • 464
  • 2
  • 6
  • 21

1 Answers1

1

Try:

       for (Path entry : stream) {
            System.out.println(entry.getFileName() + " | " + entry.toFile().isDirectory());
            if (!entry.toFile().isDirectory()) {
                list.add(entry.getFileName().toString());
            }
        }
HulkSmash
  • 386
  • 1
  • 6