How to Delete a Directory/Folder in Java using Recursion

Filed Under: Java

Earlier we learned how to create a file in java and how to delete a file in java. Here we will learn how to delete a non-empty directory/folder in java recursively.

Java Delete Directory

Java File delete() method deletes a file or an empty directory. However, if directory is not empty, it doesn’t delete it and returns false.

We will use delete() function recursively to delete a directory/folder in java program.


package com.journaldev.files;

import java.io.File;

/**
 * This utility class can be used to delete 
 * folders recursively in java
 * @author pankaj
 */
public class DeleteFolderRecursively {

    public static void main(String[] args) {
        String folder = "/Users/pankaj/tmp";
        //delete folder recursively
        recursiveDelete(new File(folder));
    }
    
    public static void recursiveDelete(File file) {
        //to end the recursive loop
        if (!file.exists())
            return;
        
        //if directory, go inside and call recursively
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                //call recursively
                recursiveDelete(f);
            }
        }
        //call delete to delete files and empty directory
        file.delete();
        System.out.println("Deleted file/folder: "+file.getAbsolutePath());
    }

}

Here we are using delete() to delete the folder contents and if it’s directory, we are recursively calling recursiveDelete method.

Here is the output of the above program which deletes the directory.


Deleted file/folder: /Users/pankaj/tmp/.DS_Store
Deleted file/folder: /Users/pankaj/tmp/data/data.dat
Deleted file/folder: /Users/pankaj/tmp/data/data.sql
Deleted file/folder: /Users/pankaj/tmp/data
Deleted file/folder: /Users/pankaj/tmp/DB.xml
Deleted file/folder: /Users/pankaj/tmp/item.xsd
Deleted file/folder: /Users/pankaj/tmp/ms/data.txt
Deleted file/folder: /Users/pankaj/tmp/ms/project.doc
Deleted file/folder: /Users/pankaj/tmp/ms
Deleted file/folder: /Users/pankaj/tmp

You can use this utility method to delete a non-empty directory.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages