Java program to delete all the files in a directory recursively (only files)


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 deletes all the files in the directory named ExampleDirectory.

import java.io.File;
import java.io.IOException;
public class DeletingAllFiles {
   public static void deleteFiles(File dirPath) {
      File filesList[] = dirPath.listFiles();
      for(File file : filesList) {
         if(file.isFile()) {
            file.delete();
         } else {
            deleteFiles(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
      deleteFiles(file);
      System.out.println("Files deleted........");
   }
}

Output

Files deleted........
raja
Published on 10-Oct-2019 14:44:52
Advertisements