如何遍历Java中的目录中的文件? [英] How do I iterate through the files in a directory in Java?

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

问题描述

我需要获取目录中所有文件的列表,包括所有子目录中的文件。使用Java完成目录迭代的标准方法是什么?

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

推荐答案

您可以使用 文件#isDirectory() 测试给定文件(路径)是否是目录。如果这是 true ,那么你只需用 文件#listFiles() 结果。这称为递归

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

这是一个基本的启动示例。

Here's a basic kickoff example.

public static void main(String... args) {
    File[] files = new File("C:/").listFiles();
    showFiles(files);
}

public static void showFiles(File[] files) {
    for (File file : files) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getName());
            showFiles(file.listFiles()); // Calls same method again.
        } else {
            System.out.println("File: " + file.getName());
        }
    }
}

请注意,这对 StackOverflowError 当树比JVM的堆栈更深时可以容纳。您可能希望使用迭代方法或尾递归,但这是另一个主题;)

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. You may want to use an iterative approach or tail-recursion instead, but that's another subject ;)

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

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