Open In App

How to List all Files in a Directory in Java?

Java provides a feature to interact with the file system through the java.io.file package. This feature helps developers automate the things to operate with files and directories.

In this article, we will learn how to list all the files in a directory in Java.



Approaches to list all files in a directory

We have two ways to get the list of all the files in a directory in Java.

Program to list all files in a directory in Java

Method 1: Using listFiles()

In the java.io.File class which provides an inbuilt method listFiles() that will return an array of File objects of the files in the directory.






// Java program list all files in a directory using listFiles()
import java.io.File;
public class ListFilesExample 
{
  
    public static void main(String[] args)
    {
      // Path of the specific directory 
      String directoryPath = "C:/Users/GFG0354/Documents/JavaCode";
        
      // Using File class create an object for specific directory
      File directory = new File(directoryPath);
        
      // Using listFiles method we get all the files of a directory 
      // return type of listFiles is array
      File[] files = directory.listFiles();
        
      // Print name of the all files present in that path
      if (files != null) {
        for (File file : files) {
          System.out.println(file.getName());
        }
      }
    }
}

Output:

Explanation of the Program:

Method 2: Using Java New I/O Package

New I/O provides a new easy way to interact with Files and apply file operations. The Files and Path classes are available in the java.nio.file package which we can use to list the files in a directory.




// Java program to list all files in a directory using I/O Package
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
  
public class NewIOExample {
  
    public static void main(String[] args) throws IOException
    {
  
        // path of the specific directory 
        String directoryPath = "C:/Users/GFG0354/Documents/JavaCode";
  
        // create a Path object for the specified directory
        Path directory = Paths.get(directoryPath);
  
        // use DirectoryStream to list files which are present in specific
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
            
          //with forEach loop get all the path of files present in directory  
            for (Path file : stream) {
                System.out.println(file.getFileName());
            }
        }
    }
}

Output:

Explanation of the Program:


Article Tags :