Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

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?

1 Answer

0 votes
by (46k points)

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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...