Friday, 22 April 2016

How to delete directories recursively ?


To delete a directory, you can simply use the File.delete(), but the directory must be empty in order to delete it.

Often times, you may require to perform recursive delete in a directory, which means all it’s sub-directories and files should be delete as well.

public static void main(String[] args) {
  String SRC_FOLDER = "C:\\shaan-new";
  File directory = new File(SRC_FOLDER);
  //make sure directory exists
  if(!directory.exists()) {
     System.out.println("Directory does not exist.");
     System.exit(0);
  } else {
    try {
      delete(directory);
    } catch(IOException e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
}

/*** Delete method using recursion ****/
public static void delete(File file) throws IOException {
  if(file.isDirectory()) {
    //if directory is empty, then delete it
    if(file.list().length==0) {
       file.delete();
       System.out.println("Directory is deleted : " + file.getAbsolutePath());
   } else {
      // list all the directory contents
      String files[] = file.list();
      for (String temp : files) {
        // construct the file structure
        File fileDelete = new File(file, temp);
        // recursive delete
        delete(fileDelete);
      }
      // check the directory again, if empty then delete it
      if(file.list().length==0) {
        file.delete();
        System.out.println("Directory is deleted : " + file.getAbsolutePath());
      }
   }
  } else {
    // if file, then delete it
    file.delete();
    System.out.println("File is deleted : " + file.getAbsolutePath());
  }
} 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.