Java Program to List Files in a Directory

Java Program to List Files in a Directory

In this tutorial, we will learn to list all the files and sub-directories present inside a directory.

The list() method of the Java File class is used to list all the files and subdirectories present inside a directory. It returns all the files and directories as a string array.


Example: List all files using list() method

import java.io.File;

class Main {
  public static void main(String[] args) {

    // creates a file object
    File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

    // returns an array of all files
    String[] fileList = file.list();

    for(String str : fileList) {
      System.out.println(str);
    }
  }
}

Output

.vscode
file.txt
directory
newFile.txt

In the above example, we have created a file object named file. The object holds information about the specified path.

File file = new File("C:\\Users\\Guest User\\Desktop\\Java File\\List Method");

We have used the list() method to list all the files and subdirectories present in the specified path.

file.list();

Note: We have used double-backslash while specifying the path. It is because the \ character is used as an escape character in Java. Hence the first backslash is used as an escape character for the second one.