How do I iterate through the files in a directory in Java?

前端 未结 10 2093
星月不相逢
星月不相逢 2020-11-22 08:37

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?

10条回答
  •  渐次进展
    2020-11-22 09:12

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

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

提交回复
热议问题