Java Function to Delete a File/Folder Recursively


On Linux Shells, we can use “rm -fr” to remove a folder and its files recursively in sub directories. On windows, we can use “del /f / s” to remove files/folders recursively.

windows-del-command Java Function to Delete a File/Folder Recursively java

Using the following Java function, we can delete a file or folder recursively platform-indenpendently.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FileUtils {
  public static boolean deleteFile(String fileName) {
    File file = new File(fileName);
    if (file.exists()) {
      // check if the file is a directory
      if (file.isDirectory()) {
        // call deletion of file individually
        Arrays.stream(Objects.requireNonNull(file.list()))
            .map(s -> fileName + System.getProperty("file.separator") + s)
            .forEachOrdered(FileUtils::deleteFile);
      }
      file.setWritable(true);
      return file.delete();
    }
    return false;
  }
}
public class FileUtils {
  public static boolean deleteFile(String fileName) {
    File file = new File(fileName);
    if (file.exists()) {
      // check if the file is a directory
      if (file.isDirectory()) {
        // call deletion of file individually
        Arrays.stream(Objects.requireNonNull(file.list()))
            .map(s -> fileName + System.getProperty("file.separator") + s)
            .forEachOrdered(FileUtils::deleteFile);
      }
      file.setWritable(true);
      return file.delete();
    }
    return false;
  }
}

We need to first check if file is existent, and then check if it is a folder (if yes, recursively calling self to remove all the files in the sub directories). Then we set the file writable to true and remove it.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
235 words
Last Post: Teaching Kids Programming - Implementation of Cartesian Product in Python via Depth First Search Algorithm
Next Post: Teaching Kids Programming - Binary Matrix Leftmost One

The Permanent URL is: Java Function to Delete a File/Folder Recursively

Leave a Reply