Delete a directory in Java

To delete a directory in Java, you will need to use the java.io package.

In the java.io package you will need to use the File class and use the delete() method.
This methods returns a boolean indicating whether or not it was successful.

1. Deleting a directory with delete()

Below you will see how I delete a directory in java using delete method.

package com.omega.tutorial;

import java.io.File;
import java.io.IOException;

public class DeleteEmptyDirectoryExample {

  public static void main(String[] args) throws IOException {

    File directory = new File("C:/tmp/dir123/");
    File directory1 = new File("C:/tmp/missing_dir/");
    String statusMsg = null;
    boolean status = false;

    //attempt to create a directory now
    boolean ok = directory.mkdir();
    if (ok) {
      System.out.format("Successfully created directory %sn", directory.getCanonicalFile());
    } else {
      System.out.println("Unable to create directory...");
    }

    //attempt to delete /tmp/dir123 directory now, should succeed
    status = directory.delete();

    // if true, return the success msg, otherwise the failed
    statusMsg = (status) ? "Successfully deleted directory": "Deletion failed for";

    //display status output of delete()
    System.out.format("%s %sn",statusMsg, directory.getCanonicalFile());

    //attempt to delete C:/tmp/missing_dir/ directory now, should fail
    status = directory1.delete();

    // if true, return the success msg, otherwise the failed
    statusMsg = (status) ? "Successfully deleted directory": "Deletion failed for";

    //display status output of delete()
    System.out.format("%s %sn",statusMsg, directory1.getCanonicalFile());
  }
}

Output:

delete_directory

2. Deleting a non-empty directory recursively

Now we will show you how to recursively delete files and folders using java.io.File.delete() method.  This will effectively delete all files and folders from a non-empty directory.

package com.omega.tutorial;

import java.io.File;
import java.io.IOException;

public class DeleteAllFilesAndDirectoriesExample {

  public static void main(String[] args) throws IOException {
    // Delete the folder named "/tmp/dir1" including the entire contents
    System.out.println("Attempting to delete the entire folder and all contents of C:/tmp/dir1");
    File folder = new File("C:/tmp/dir1");
    deleteAllFiles(folder);
  }

  public static void deleteAllFiles(File dirName) {
    if (dirName.exists()) {
      if (dirName.isDirectory()) {
        String[] filenames = dirName.list();
        for (String f : filenames) {
          deleteAllFiles(new File(dirName, f));
        }
      }
      System.out.println("Deleting " + dirName.getName());
      dirName.delete();
    }
  }
}

3. Testing it out in more depth

The below example uses the method shown above, however, we will be creating a nested directory structure first with some dummy text files so that we can see the program in action.

package com.omega.tutorial;

import java.io.File;
import java.io.IOException;

public class DeleteAllFilesAndDirectoriesExample {

  public static void main(String[] args) throws IOException {
    boolean ok = false;

    // create the following deep nested tree structure
    System.out.println("Creating the directories C:/tmp/dir1/sublevel1/sublevel2/sublevel3");
    ok = new File("C:/tmp/dir1/sublevel1/sublevel2/sublevel3").mkdirs();

    // create a three blank files in sublevel1 directory
    // I'm ignoring the "ok" return code from the createNewFile to simplify the code
    System.out.println("Creating the files file1.txt, file2.txt, file3.txt in C:/tmp/dir1/sublevel1");
    ok = new File("C:/tmp/dir1/sublevel1/file1.txt").createNewFile();
    ok = new File("C:/tmp/dir1/sublevel1/file2.txt").createNewFile();
    ok = new File("C:/tmp/dir1/sublevel1/file3.txt").createNewFile();

    // Wait for 3 seconds, so you can see files
    try {
        Thread.sleep(3000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    // Delete the folder named "/tmp/dir1" including the entire contents
    System.out.println("Attempting to delete the entire folder and all contents of C:/tmp/dir1");
    File folder = new File("C:/tmp/dir1");
    deleteAllFiles(folder);
  }

  public static void deleteAllFiles(File dirName) {
    if (dirName.exists()) {
      if (dirName.isDirectory()) {
        String[] filenames = dirName.list();
        for (String f : filenames) {
          deleteAllFiles(new File(dirName, f));
        }
      }
      System.out.println("Deleting " + dirName.getName());
      dirName.delete();
    }
  }
}

Output:

delete_directory2

Other Related Posts

  • How to Get Disk Space in Java
    Getting file statistics (ie. disk space) can now be easily done in Java 1.6 using new methods that we recently released.
  • Creating Directory in Java
    Learn how to create directories using these easy to follow instructions.
  • Delete a directory in Java
    Learn how to delete a directory using these easy to follow instructions. In the java.io package you will need to use the File class and use the delete() method.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *