如何在Java中扫描文件夹? [英] How to scan a folder in Java?

查看:34
本文介绍了如何在Java中扫描文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中递归地列出文件夹中的所有文件?

How can I get list all the files within a folder recursively in Java?

推荐答案

不确定要如何表示树?无论如何,这是一个使用递归扫描整个子树的示例.文件和目录被同等对待.请注意 File.listFiles() 对于非目录返回 null.

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

public static void main(String[] args) {
    Collection<File> all = new ArrayList<File>();
    addTree(new File("."), all);
    System.out.println(all);
}

static void addTree(File file, Collection<File> all) {
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            all.add(child);
            addTree(child, all);
        }
    }
}

Java 7 提供了一些改进.例如,DirectoryStream 一次提供一个结果 - 调用者不再需要等待所有 I/O 操作完成后才采取行动.这允许增量 GUI 更新、提前取消等.

Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

static void addTree(Path directory, Collection<Path> all)
        throws IOException {
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
        for (Path child : ds) {
            all.add(child);
            if (Files.isDirectory(child)) {
                addTree(child, all);
            }
        }
    }
}

请注意,可怕的 null 返回值已被 IOException 替换.

Note that the dreaded null return value has been replaced by IOException.

Java 7 还提供了一个 tree walker::>

Java 7 also offers a tree walker:

static void addTree(Path directory, final Collection<Path> all)
        throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            all.add(file);
            return FileVisitResult.CONTINUE;
        }
    });
}

这篇关于如何在Java中扫描文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆