Join our newsletter for the latest updates.
Java Program to Get all Files Present in a Directory

Java Program to Get all Files Present in a Directory

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

To understand this example, you should have the knowledge of the following Java programming topics:


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 1: Java Program to List all files

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.


Example 2: List files present in a Directory excluding Subdirectories

import java.io.File;

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

    try {

      File folder = new File("C:\\Users\\Sudip Bhandari\\Desktop\\Java Article");

      // list all the files
      File[] files = folder.listFiles();
      for(File file : files) {
        if(file.isFile()) {
          System.out.println(file);
        }
      }
    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output

C:\Users\Unknown\Desktop\Java Article\Language.class
C:\Users\Unknown\Desktop\Java Article\Languages.class
C:\Users\Unknown\Desktop\Java Article\Main.class
C:\Users\Unknown\Desktop\Java Article\Main.java
C:\Users\Unknown\Desktop\Java Article\sidebar.html
C:\Users\Unknown\Desktop\Java Article\Test.class
C:\Users\Unknown\Desktop\Java Article\Time.class
C:\Users\Unknown\Desktop\Java Article\Time.java

In the above example, we have used the listFiles() method to store all files in an array.