How to list files in directory in Java

August 17, 2020 No comments Java IO Files list Java

1. Introduction

Managing files is a common functionality used in many applications that need to save permanently important data or static resources like images or documents. In this tutorial, we are going to show how to list files in a specific directory using plain Java methods.

2. List files using File.listFiles(...)

To list files from a folder without going deep into sub-directories we can use the Files.listFiles(...) method:

package com.frontbackend.java.io.list;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class ListFilesUsingFile {

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

        Arrays.stream(file.listFiles())
              .forEach(System.out::println);

        Arrays.stream(file.listFiles(file1 -> file1.getName()
                                                   .endsWith(".txt")))
              .forEach(System.out::println);
    }
}

In this example, we use listFiles(...) method to print all files from /tmp folder. The second part of our main uses the FileFilter object that we can provide as a listFiles(...) method parameter. This allows us to filter files and prints only resources with specific extension - .txt in our case.

3. Print files from directory using DirectoryStream from Java 7

In Java 7 we have a dedicated stream object called DirectoryStream for listing files in a directory.

Let's check the example code:

package com.frontbackend.java.io.list;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ListFilesUsingDirectoryStream {

    public static void main(String[] args) throws IOException {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("/tmp"))) {
            stream.forEach(path -> {
                if (!Files.isDirectory(path)) {
                    System.out.println(path.getFileName()
                                           .toString());
                }
            });
        }
    }
}

In this example we used Files.newDirectoryStream(...) method to create new DirectoryStream<Path> stream. Then we iterate over each item in the stream and print filenames but only for files: Files.isDirectory(...).

4. List files from a folder using Files.walk(...) method

We can list files from directory using Files.walk method that allows us to navigate over folder structure:

package com.frontbackend.java.io.list;

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 ListFilesUsingFiles {

    public static void main(String[] args) throws IOException {
        try (Stream<Path> stream = Files.walk(Paths.get("/tmp"), 1)) {
            stream.filter(file -> !Files.isDirectory(file))
                  .map(Path::getFileName)
                  .map(Path::toString)
                  .forEach(System.out::println);
        }
    }
}

To make sure that JDK will close the resource we used try-with-resources syntax. In this example first, we created stream Stream<path> using Files.walk method. Then we retrieved the necessary value from our complex object.

5. Conclusion

In this article, we presented several methods to list files in a directory using Java. There are several ways to achieve that, choose the one that is the best for you.

{{ message }}

{{ 'Comments are closed.' | trans }}