Monday 23 October 2017

Delete a directory recursively in Java

In this post, I am going to show you how to delete a directory recursively in Java.

PseudoCode.
Step 1: First check whether given file exists or not.
Step 2: If file is not exist return.
Step 3: If file is a directory, then read all the children from given directory. For every children, if the children is a directory then repeat step 3 and delete the file.

Find the below working application.

FileUtil.java
package utils;

import java.io.File;

public class FileUtil {
 public static void deleteDirectory(String dirName) {
  if (dirName == null || dirName.isEmpty()) {
   throw new IllegalArgumentException("File name shouldn't be empty");
  }
  File file = new File(dirName);

  if (!file.exists()) {
   System.out.println("File is not existed");
   return;
  }

  if (file.isDirectory()) {
   deleteDirectory(file);
   file.delete();
  }

 }

 private static void deleteDirectory(File dir) {

  File[] children = dir.listFiles();

  for (File file : children) {
   if (file.isDirectory()) {
    deleteDirectory(file);
   }
   file.setWritable(true);
   file.delete();
  }

 }
}


Test.java
package utils;

public class Test {

 public static void main(String args[]) {
  String dirName = ""; // Directory absolute path to delete
  FileUtil.deleteDirectory(dirName);

 }
}

No comments:

Post a Comment