ZetCode

Java list directory contents

last modified February 21, 2024

In this article we 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.

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

void main() throws IOException {

    String dirName = "..";

    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.

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

void main() throws IOException {

    String pathName = "..";

    try (Stream<Path> paths = Files.walk(Paths.get(pathName))) {
        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 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.

Main.java
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;

void main() throws IOException {

    String dirName = "..";
    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.

Main.java
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;

void main() throws IOException {

    String dirName = "..";
    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.

Main.java
import java.io.File;

void main() {

    String dirName = "..";

    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.

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

List<File> files = new ArrayList<>();

void main() {

    String dirName = "..";
    File file = new File(dirName);

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

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.

Listing directory contents with Apache commons IO

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

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

void main() {

    String dirName = ".";

    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.

$ java -cp commons-io-2.15.1.jar Main.java

We run the program. We pass the commons-io-2.15.1.jar to the classpath.

Source

Java Basic I/O

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

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials.