简体   繁体   English

如何使用Java的目录流仅在目录中而不是其他子目录中获取文件/子目录

[英]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. 我正在使用Java的DirectoryStream来获取目录中所有文件/子文件夹的列表。 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());
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java,仅列出目录中的子目录,而不是文件 - Java, List only subdirectories from a directory, not files 如何使用 Java 中的 glob 来匹配目录和子目录中的文件? - How can I use a glob in Java to match files in directory and subdirectories? 获取目录及其子目录中的文件数 - get number of files in a directory and its subdirectories 如何使用正则表达式获取目录中不包含子目录的所有文件? - How to get all files in a directory with exclusion of subdirectories using regular expression? 带有文件和子目录的zip目录,在Java中没有绝对路径 - zip directory with files and subdirectories without the absolute path in Java 删除所有文件和子目录,但在Java中保持当前目录为空 - Delete all files and subdirectories but keep the current directory empty in Java 在 Java 中递归压缩包含任意数量的文件和子目录的目录? - Recursively ZIP a directory containing any number of files and subdirectories in Java? Amzon s3 Java API列出基本目录的子目录 - Amzon s3 Java API to list subdirectories of base directory 以递归方式获取Java中的目录及其子目录中的所有文件 - Non-recursive way to get all files in a directory and its subdirectories in Java 如何在hadoop hdfs中列出目录及其子目录中的所有文件 - How to list all files in a directory and its subdirectories in hadoop hdfs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM