How to list all files in the directory

In this tutorial we will find out how to list all files and folders in the specified directory.

Java 6

Listing all the files and directories in the specified directory (flat structure):

public void listFilesForFolder(File directory) {
    File[] files = directory.listFiles();
    for (File file : files) {
        System.out.println(file);
    }
}

Listing all files and directories recursively (including subdirectories):

public void listFilesForFolderRecursively(File directory) {
    for (File file : directory.listFiles()) {
        if (file.isDirectory()) {
            listFilesForFolderRecursively(file);
        } else {
            System.out.println(file);
        }
    }
}

Java 8

Listing all the files and directories in the specified directory (flat structure) using Files.list() method:

public void listFilesForFolderUsingFilesList(String directory) throws IOException {
    Files.list(Paths.get("."))
            .forEach(System.out::println);
}

Listing all the files and directories in the specified directory (flat structure) using Files.newDirectoryStream() method:

public void listFilesForFolderUsingNewDirectoryStream(String directory) throws IOException {
    Files.newDirectoryStream(Paths.get("."))
            .forEach(System.out::println);
}

Listing all files and directories recursively using Files.walk() method .

public void listFilesForFolderJava8Recursively(String directory) throws IOException {
    Files.walk(Paths.get(directory))
            .forEach(System.out::println);
}

Leave a Reply

Your email address will not be published. Required fields are marked *