How do I list files in a given directory using Files.list() method?

In Java, you can use the Files.list() method to list all files in a given directory. Files.list(Path dir) is a method in the java.nio.file.Files class.

This method returns a Stream that is lazily populated with Path by walking the directory tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the name of the directory entry against dir.

The stream is “lazy” because not all the Paths are populated at once. This can be beneficial if you have a large number of files in your directory.

Here’s a code snippet that shows you how to do it:

package org.kodejava.io;

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 ListFiles {
    public static void main(String[] args) {
        // Replace with your directory
        Path path = Paths.get("D:/Games");

        // Use try-with-resources to get auto-closeable stream
        try (Stream<Path> paths = Files.list(path)) {
            paths
                    .filter(Files::isRegularFile)  // filter out subdirectories
                    .forEach(System.out::println); // print file names
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code lists all files in the specified directory ("D:/Games" in this case). It uses a stream of Path obtained from Files.list(), filters out the paths that are not regular files using Files.isRegularFile(), and finally prints each file name using System.out.println().

Remember to replace "D:/Games" with the actual directory you want to list files from. Also, the Files.list() method throws an IOException, so you must handle this exception in a try-catch block or declare it in the method signature.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.