How to use Java's directory stream to get files/subdirectories only within directory not other subdirectories

2.4k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

Try:

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