Languages
[Edit]
EN

Java - list all files from directory

0 points
Created by:
Emrys-Li
580

In this article, we would like to show you how to list all file names from the directory in Java.

Quick solution:

File[] files = new File(path).listFiles(File::isFile); // get array of files

 

Practical example

In this example, we use listFiles() method and check if the file is a file (not a directory) to list only files from the directory specified by path.

Java - list all files (example data)
Java - list all files (example data)

Code example:

import java.io.File;
import java.util.Objects;

public class Example {

    public static void main(String[] args) {

        String path = "C:\\projects\\example";
        File[] files = new File(path).listFiles(File::isFile); // array of files

        File[] list = Objects.requireNonNull(files); // creates list if files!= null

        for (File item : list) {
            System.out.println(item.getName());
        }
    }
}

Result:

file1.txt
file2.json
file3.pdf

Note:

To get full file paths instead of file names remove getName() from item.getName() inside for loop.

Result:

C:\projects\example\file1.txt
C:\projects\example\file2.json
C:\projects\example\file3.pdf

References

Alternative titles

  1. Java - list only files from directory
  2. Java - list all file names from directory
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join