Delete a directory in Java



The method java.io.File.delete() can be used to delete the directory with the required abstract path name. This method requires no parameters and it returns true on the successful deletion of the directory and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      boolean flag;
      String directory = "D:\a";
      File file = new File(directory);
      flag = file.mkdir();
      System.out.println("The directory is created? " + flag);
      flag = file.delete();
      System.out.println("The directory is deleted? " + flag);
   }
}

The output of the above program is as follows −

Output

The directory is created? true
The directory is deleted? true

Now let us understand the above program.

The directory is created and then deleted using the method java.io.File.delete(). Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −

boolean flag;
String directory = "D:\a";
File file = new File(directory);
flag = file.mkdir();
System.out.println("The directory is created? " + flag);
flag = file.delete();
System.out.println("The directory is deleted? " + flag);
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements