List all the files in a directory in Java

In this program, we list all the files present in a given folder/directory in Java, and if this directory consists of other nested sub-directories, it lists the file from there also.

We use a simple recursion algorithm to the following, and it is quite easy to obtain so.

Recursive algorithm to list all the files:

1. We first create the File object for the main directory.

2. Then we get an array of files for main directory.

3. If the array[i] is a file, then we print out the file name.

4. If the array[i] is a directory, then we print out directory name. Then get an array of files for current sub-directory and repeat step 3 and 4 with current sub-directory.

5. We then repeat steps 3 and 4 with next array[i].

Implementation in Java:

To list all the files in a directory, below is our Java code:

public class ListFiles  
     static void FileCall(File[] arr,int index,int level)  
         if(index == arr.length)          // this terminates condition 
         for (int i = 0; i < level; i++)  // tabs are printed for internal levels
             System.out.println(arr[index].getName()); // prints for files 
         else if(arr[index].isDirectory()) 
             System.out.println("[" + arr[index].getName() + "]");          // printed for sub-directories and helps distinguish
             FileCall(arr[index].listFiles(), 0, level + 1);          // recursion for sub-directories
        FileCall(arr,++index, level);          // this recursion is done for the main directory 
    public static void main(String[] args) 
        String directory = "C:\\Users\\Vedant\\Desktop\\Codespeedy"; // Provide the full path for your directory and change it accordingly
        File maindirectory = new File(directory); //object to create fie
        if(maindirectory.exists() && maindirectory.isDirectory()) 
            File arr[] = maindirectory.listFiles(); // this array consists of files and sub directories 
            System.out.println("Files from main directory : " + maindirectory);             
            FileCall(arr,0,0);    // Calling recursive method 

The output of the code:

If we run our program, we will able to see the output that is something like you can see below:

Files from main directory : C:\Users\Vedant\Desktop\Codespeedy 

As seen above, the program is successfully implemented and is easy to do so with the help of the recursive function. We can see all the files of the directory.

You can also refer to:
Detect If A File Exists or Not in A particular Directory with Java

Leave a Reply

Your email address will not be published. Required fields are marked *