How to delete folder and sub folders using Java?

Java 8Object Oriented ProgrammingProgramming

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.

The delete() method of the File class deletes the file/directory represented by the current File object.

This ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

Therefore, to delete a folder along with its sub directories and files, you need to define a recursive method.

Example

Following Java program deletes the specified directory recursively −

import java.io.File;
public class DeletingFilesRecursively {
   static void deleteFolder(File file){
      for (File subFile : file.listFiles()) {
         if(subFile.isDirectory()) {
            deleteFolder(subFile);
         } else {
            subFile.delete();
         }
      }
      file.delete();
   }
   public static void main(String args[]) {
      String filePath = "E://ExampleDirectory//";
      //Creating the File object
      File file = new File(filePath);
      deleteFolder(file);
      System.out.println("Files deleted........");
   }
}

Output

Files deleted........

Using ApacheCommonsIO

The deleteDirectory() method of the ApacheCommonsIO accepts a file path and directory deletes it recursively.

Maven dependency

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>

Example

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DeletingFilesRecursively2 {
   public static void main(String args[]) throws IOException {
      String filePath = "E://ExampleDirectory//";
      //Creating the File object
      File file = new File(filePath);
      FileUtils.deleteDirectory(file);
      System.out.println("Files deleted........");
   }
}

Output

Files deleted........
raja
Published on 02-Aug-2019 12:13:29
Advertisements