Low Orbit Flux Logo 2 D

Java How To Delete A Directory With Files ( Recursive )

In Java it is possible to delete a directory that contains files but it isn’t as straightforward as you might hope. You will need to either delete the files first or use a third party library that does this for you.

The Easy Way - Apache Commons IO

Here is an example showing how you can do this using a third party library called Apache Commons IO. This library contains many useful functions that will save you time and effort. In this case we just need to call FileUtils.deleteDirectory(), pass it a file, and catch the thrown IOException.

You can learn more about how to install Apache Commons IO in our other guide here: How to Install Apache Commons io Java.

import org.apache.commons.io.*;
import java.io.*;

class Test1 {
   public static void main( String args[] ) {
       try {
           FileUtils.deleteDirectory(new File("delete_me"));
       }
       catch (IOException e) {
               System.out.println("IOException");
       }
   }
}

Built-in Java Libraries - How to Recursively Delete a Directory with Files

Here is an example showing you you can recursively delete files using only built-in Java libraries.

import java.io.*;

class Test1 {

    public void remove(File file1){
        File[] files = file1.listFiles();
        for (File file2 : files) {

            if( file2.isFile() ) {
                file2.delete();
            }
            if( file2.isDirectory() ) {
                remove(file2);
                file2.delete();
            }
            System.out.println(file2);
        }
        file1.delete();
    }

    public static void main( String args[] ) {
        Test1 t = new Test1(); 
        t.remove(new File("delete_me"));
    }
}

Other Methods

You can also achieve similar results using: