Java program to List all files in a directory recursively


Assume we have a folder named ExampleDirectory in the directory D with 7 files and 2 directories as −

Where,

  • SampleDirectory1 contains two files named SampleFile1.txt and SampleFile2.txt.

  • SampleDirectory2 contains two files named SampleFile2.txt and SampleFile3.txt.

Example

Following Java example lists the names of all the files in the directory named ExampleDirectory.

import java.io.File;
import java.io.IOException;
public class ListOfFiles {
   public static void listOfFiles(File dirPath){
      File filesList[] = dirPath.listFiles();
      for(File file : filesList) {
         if(file.isFile()) {
            System.out.println("File path: "+file.getName());
         } else {
            listOfFiles(file);
         }
      }
   }
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File file = new File("D:\\ExampleDirectory");
      //List of all files and directories
      listOfFiles(file);
   }
}

Output

File path: cassandra_logo.jpg
File path: cat.jpg
File path: coffeescript_logo.jpg
File path: javafx_logo.jpg
File path: SampleFile1.txt
File path: SampleFile2.txt
File path: SampleFile4.txt
File path: SapmleFile3.txt
File path: SampleHiddenfile1.txt
File path: SampleHiddenfile2.txt
File path: SampleHiddenfile3.txt
raja
Published on 10-Oct-2019 14:40:50
Advertisements