Java program to List all files in a directory and nested sub-directory - Recursive approach


To list all files in a directory and nested sub-directory, the Java program is as follows −

Example

import java.io.File;
public class Demo{
   static void print_recursively(File[] my_arr,int my_index,int sub_level){
      if(my_index == my_arr.length)
      return;
      for (int i = 0; i < sub_level; i++)
         System.out.print("\t");
      if(my_arr[my_index].isFile())
         System.out.println(my_arr[my_index].getName());
      else if(my_arr[my_index].isDirectory()){
         System.out.println("[" + my_arr[my_index].getName() + "]");
         print_recursively(my_arr[my_index].listFiles(), 0, sub_level + 1);
      }
      print_recursively(my_arr,++my_index, sub_level);
   }
   public static void main(String[] args){
      String path_main = "path to folder that contains files";
      File main_dir = new File(path_main);
      if(main_dir.exists() && main_dir.isDirectory()){
         File my_arr[] = main_dir.listFiles();
         System.out.println("Files listed from the main directory are : " + main_dir);
         print_recursively(my_arr,0,0);
      }
   }
}

Output

Inside the directory path, all the files of all formats from the path will be listed

A class named Demo contains a function named ‘print_recursively’ that takes the array and the index value, and nested levels as parameters, and iterates through the files and returns the list of all files in that specific directory.

In the main function, the path to the folder with all the files is defined and a new file path is also created. The ‘listFiles’ function is used to list all the files in that specific folder. Next, the function is called by passing these parameters. Result is displayed on the console.

Updated on: 14-Jul-2020

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements