简体   繁体   中英

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

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

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM