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:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

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

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}
Answer from BalusC on Stack Overflow
Top answer
1 of 11
251

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:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

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

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}
2 of 11
101

If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...).

For example:

public class WalkFileTreeExample {

  public static void main(String[] args) {
    Path p = Paths.get("/usr");
    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
      }
    };

    try {
      Files.walkFileTree(p, fv);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...):

public class WalkFileTreeExample {

  public static void main(String[] args) {
    try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {
      paths.forEach(System.out::println);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › listing all files in a directory in java
Listing All Files in a Directory in Java
October 1, 2022 - Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively. For using external iteration (for loop) use DirectoryStream.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio
Java Nio Iterate Over Files in Directory - Java Code Geeks
March 12, 2019 - We check if the Path is a directory Paths.isDirectory(...)and if it is we create our own Directory proxy to encapsulate the specific Path and recursively iterate again. Should it be a file, we create our own File proxy to encapsulate the file and add it to the current Directory proxy we are currently listing. lines 58-67: we create a Filter that matches all directories and any files that contain the given pattern in their names.
🌐
Quickprogrammingtips
quickprogrammingtips.com › java › how-to-iterate-through-a-directory-tree-in-java.html
How to Iterate Through a Directory Tree in Java
walkDirTreeAndSearch - Walks through the directory and prints file/directory names matching the search criteria. This method can be used for recursive file search. import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Paths; // Java sample program to iterate through directory tree // Uses the Files.walk method added in Java 8 public class WalkDirectoryTree { public static void main(String[] args) throws Exception { // in windows use the form c:\\folder String rootFolder = "/Users/jj/temp"; walkDirTree(rootFolder); walkDirTreeWithSymLinks(rootFolder); String searchFor = "png"; walkDirTreeAndSearch(rootFolder, searchFor); } // Prints all file/directory names in the entire directory tree!
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-list-all-files-in-a-directory-recursively
Java program to List all files in a directory recursively
May 12, 2025 - Following is the code to list all the files in a directory recursively using the Files.walk() method: import java.io.*; import java.nio.file.*; import java.util.stream.*; public class ListFilesRecursively { public static void main(String[] args) { // Create a Path object for the directory Path ...
Find elsewhere
🌐
CodeJava
codejava.net › java-se › file-io › list-files-and-directories-recursively-in-a-directory
Java File IO - List files and directories recursively
July 29, 2019 - import java.io.File; /** * * @author www.codejava.net * */ public class ListDirectoryRecurisve { public void listDirectory(String dirPath, int level) { File dir = new File(dirPath); File[] firstLevelFiles = dir.listFiles(); if (firstLevelFiles != null && firstLevelFiles.length > 0) { for (File aFile : firstLevelFiles) { for (int i = 0; i < level; i++) { System.out.print("\t"); } if (aFile.isDirectory()) { System.out.println("[" + aFile.getName() + "]"); listDirectory(aFile.getAbsolutePath(), level + 1); } else { System.out.println(aFile.getName()); } } } } public static void main(String[] args
🌐
JavaMadeSoEasy
javamadesoeasy.com › 2015 › 08 › program-to-traverse-directory-all-sub.html
JavaMadeSoEasy.com (JMSE): Program to Traverse a Directory (all sub-directories and files) in 2 ways | using org.apache.commons.io.FileUtils in java file IO
java.io.File does not provide any direct method to iterate over Directory · we'll write method traveseSubDirAndFiles() which recursively displays all sub-directories and files present in that directory · Must read Directory operations - create, ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-traverse-in-a-directory
Java Program to Traverse in a Directory - GeeksforGeeks
July 23, 2025 - // Java Program to Traverse Through a Directory // Importing required classes import java.io.File; // Main class class GFG { // Method 1 // To display files public static void displayFiles(File[] files) { // Traversing through the files array for (File filename : files) { // If a sub directory is found, // print the name of the sub directory if (filename.isDirectory()) { System.out.println("Directory: " + filename.getName()); // and call the displayFiles function // recursively to list files present // in sub directory displayFiles(filename.listFiles()); } // Printing the file name present in
🌐
Blogger
javarevisited.blogspot.com › 2021 › 05 › how-to-recursively-list-all-files-in-java.html
How to recursively show all files in a directory and sub-directory in Java - Example
Java programmers should use this if they are developing a recursive copy, a recursive move, a recursive delete, or a recursive operation that sets permissions or performs another operation on each of the files. If you like to use third-party open-source utility libraries like Apache Commons-IO then you can also use their FileUtils class which has iterateFiles() and listFiles() methods.
🌐
Attacomsian
attacomsian.com › blog › java-traverse-directory-structure
How to traverse a directory structure in Java
December 15, 2019 - In Java 8 and higher, you can use the Files.walk() method from Java NIO API to iterate through all files and sub-directories in a particular directory as shown below: try (Stream<Path> files = Files.walk(Paths.get("dir"))) { // traverse all ...
🌐
Baeldung
baeldung.com › home › java › java io › listing files recursively with java
Listing Files Recursively With Java | Baeldung
August 18, 2024 - This method uses Apache Commons IO’s FileUtils.iterateFiles() to create an iterator over all files in a directory, then prints each file’s absolute path. Additionally, second parameter of this method allows us to filter files by its extension (e.g: {“java”, “xml”}). In this case it is defaulted to null, so no files are filtered out. And with the last parameter we can easily decide if we want this iteration to be recursive for all subdirectories.
🌐
ZetCode
zetcode.com › java › directorystream
Java DirectoryStream - iterating over directories with DirectoryStream
List<Path> paths = new ArrayList<>(); List<Path> walk(Path path) throws IOException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { for (Path entry : stream) { if (Files.isDirectory(entry)) { walk(entry); } paths.add(entry); } } return paths; } void main() throws IOException { var myPath = Paths.get("C:/Users/Jano/Downloads"); var paths = walk(myPath); paths.forEach(System.out::println); } The example walks over the directory recursively. It collects all the entries in a list and prints them out.
🌐
GeeksforGeeks
geeksforgeeks.org › java › list-all-files-from-a-directory-recursively-in-java
List all Files from a Directory Recursively in Java - GeeksforGeeks
April 28, 2025 - It calls the listAllFiles method to recursively list all files in the root directory. The listAllFiles method uses a DirectoryStream to iterate over the entries in the current directory.
🌐
CodingTechRoom
codingtechroom.com › question › iterate-directory-files-java
How to Iterate Through Files in a Directory and Its Subdirectories in Java - CodingTechRoom
import java.io.File; public class ... } } } } To iterate through files in a directory and its subdirectories in Java, you can utilize the `File` class to navigate the directory structure....