Java list directory contents

Java list directory tutorial shows how to display directory contents in Java.

Directory definition

Directory is an organizing unit in a computer's file system for storing and locating files. Directories are hierarchically organized into a tree of directories. Directories have parent-child relationships.

Java list directory classes

We can use the following Java classes to list directory contents:

List directory contents non-recursively with Files.list

The Files.list() method returns a lazily populated stream of Path objects. The listing is not recursive.

JavaFilesList.java
package com.zetcode;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class JavaFilesList {

    public static void main(String[] args) throws IOException {

        String dirName = "/home/janbodnar/prog/";

        Files.list(new File(dirName).toPath())
                .limit(10)
                .forEach(path -> {
                    System.out.println(path);
                });
    }
}

This example displays ten files or directories from the given directory.

List directory contents recursively with Files.walk

The Files.walk() method returns a lazily populated stream of Paths by walking the file tree rooted at a given starting file. Files.walk() recursively walks all subdirectories.

JavaFilesWalk.java
package com.zetcode;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class JavaFilesWalkFilter {

    public static void main(String[] args) throws IOException {
        try (Stream<Path> paths = Files.walk(Paths.get("/home/janbodnar/prog"))) {
            paths.filter(Files::isRegularFile)
                    .forEach(System.out::println);
        }
    }
}

This example displays the contents of the given directory with Files.walk() method. With the filter() method, we filter the contents of the directory to include only regular files.

Listing directory contents with Apache commons IO

Apache commons' FileUtils.listFiles() allows to list directory contents both recursively and non-recursively.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

For the example we need this dependency.

JavaDirectoryContentsApacheCommons.java
package com.zetcode;

import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class JavaDirectoryContentsApacheCommons {
    
    public static void main(String[] args) {
        
        String dirName = "/home/janbodnar/tmp/";
        
        List<File> files = (List<File>) FileUtils.listFiles(new File(dirName), null, true);
        
        files.forEach(System.out::println);
    }
}

The code example displays the directory contents recursively with FileUtils.listFiles().

List<File> files = (List<File>) FileUtils.listFiles(new File(dirName), null, true);

The first parameter of the FileUtils.listFiles() is the directory name to be listed. The second parameter is the array of extensions that should match the listing. If null is given, all files are returned. The third parameter determines if the listing is recursive; that is, all subdirectories are searched as well.

Listing directory contents non-recursively with Files.walkFileTree

Files.walkFileTree() method walks a file tree rooted at a given starting file. It uses a FileVisitor pattern which specifies the required behavior at key points in the traversal process: when a file is visited, before a directory is accessed, after a directory is accessed, or when a failure occurs.

JavaWalkFilesTree.java
package com.zetcode;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;

public class JavaWalkFilesTree {

    public static void main(String[] args) throws IOException {
        
        String dirName = "/home/janbodnar/prog";
        File file = new File(dirName);

        Files.walkFileTree(file.toPath(), Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println(file);
                return FileVisitResult.CONTINUE;
            }
        });        
    }
}

The example uses Files.walkFileTree() to traverse a directory non-recursively.

Files.walkFileTree(file.toPath(), Collections.emptySet(), 1, new SimpleFileVisitor<Path>() {

The Files.walkFileTree() parameters are: the starting file, the options to configure the traversal, the maximum number of directory levels to visit, the file visitor to invoke for each file. In our case we have one directory level to traverse.

Listing directory contents recursively with Files.walkFileTree

In the following example, we use Files.walkFileTree() to traverse the whole directory structure.

JavaWalkFilesTree.java
package com.zetcode;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class JavaWalkFilesTree {

    public static void main(String[] args) throws IOException {
        String dirName = "/home/janbodnar/prog";
        File file = new File(dirName);

        Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

The example uses an overloaded Files.walkFileTree() method to traverse a directory recursively.

Listing directory contents non-recursively with File

The java.io.File class is an older API to list directory contents. It is not as powerful as the modern API, mentioned earlier. The File's listFiles() returns an array of file objects in the given directory.

JavaDirectoryContentsFile.java
package com.zetcode;

import java.io.File;

public class JavaDirectoryContentsFile {

    public static void main(String[] args) {

        String dirName = "/home/janbodnar/tmp/";
        
        File fileName = new File(dirName);
        File[] fileList = fileName.listFiles();
        
        for (File file: fileList) {
            
            System.out.println(file);
        }
    }
}

The example prints the contents of the given directory to the console. It does not go into subdirectories.

Listing directory contents recursively with File

This time we use java.io.File class to recursively list the directory.

JavaDirectoryContentsFileRecursive.java
package com.zetcode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class JavaDirectoryContentsFileRecursive {

    private static List<File> files = new ArrayList<>();
    
    public static void main(String[] args) {

        String dirName = "/home/janbodnar/tmp/";

        File file = new File(dirName);
        
        List<File> myfiles = doListing(file);
        
        myfiles.forEach(System.out::println);
    }

    public static List<File> doListing(File dirName) {

        File[] fileList = dirName.listFiles();
        
        for (File file : fileList) {
        
            if (file.isFile()) {
            
                files.add(file);
            } else if (file.isDirectory()) {
            
                files.add(file);
                doListing(file);
            }
        }
        
        return files;
    }
}

The doListing() method lists the contents of a directory. We determine if the file is a directory with isDirectory() method and recursively call doListing() on each subdirectory.

In this tutorial, we have shown various ways to list directory contents in Java.

You might also be interested in the following related tutorials: Reading text files in Java, Java append to tile, Copying file in Java, Java tutorial, Joining strings with Java 8's StringJoiner, Reading a web page in Java, or Introduction to Google Guava.