tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > Delete Directory

Delete Directory 

The following example shows how to delete a non empty directory. The delete method deletes the directory if and only if the directory is empty. To delete a non empty directory, we need to recursive delete all its content and finally the actually directory.

File Name  :  
com/bethecoder/tutorials/io/DeleteDirectory.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

import java.io.File;

public class DeleteDirectory {

  /**
   @param args
   */
  public static void main(String[] args) {
    File dir2Delete = new File("C:\\ABC");

    //dir2Delete.delete() returns
    //true if and only if the file or directory is successfully deleted; false otherwise 
    //NOTE : The directory will not be deleted unless the directory is empty
    //       So to delete a directory we need to delete its contents recursively.
    System.out.println("File deleted successfully : " + dir2Delete.delete());
    
    /**
     * Delete the directory content recursively.
     */
    System.out.println("File deleted successfully : " + deleteDirectory(dir2Delete));
  }
  
  public static boolean deleteDirectory(File file2Delete) {

    //Delete contents of directory if the current
    //file referring is a directory
    if (file2Delete.isDirectory()) {
      
      File [] children = file2Delete.listFiles();
      
      for (int i = ; i < children.length ; i ++) {
        deleteDirectory(children[i]);
      }
    }
    
    return file2Delete.delete();
  }

}
   

It gives the following output,
File deleted successfully : false
File deleted successfully : true



 
  


  
bl  br