Saturday, 29 November 2014

How to delete a directory in Java


Well lately I have written a lot of code for file manipulation, I/O etc. So let me take this post to show how can we create or delete directories. Well Java provides APIs for them so it should be pretty straightforward to understand. Important point to look forward is that if you are deleting a directory and it has more files in it then the directory will not get deleted unless all it's children are deleted recursively.  Note File as a Java object can represent either a file or a directory. You can use File 's class isDirectory() method Eg.

        File file = new File("C:\\Users\\athakur\\Downloads");
        if(file.isDirectory()) {
            System.out.println("File is a directory");

Now lets get to creating and deleting directories/files.

Creating a File

To create a file we can use createNewFile() method. Eg - 

        File file = new File("C:\\Users\\athakur\\Downloads\\abc.txt");
        if(!file.exists()) {

Creating a Directory

To create a directory first create a File object and then call mkdir() on it. Eg -

        File file = new File("C:\\Users\\athakur\\Downloads\\Movies");
        if(!file.exists()) {

Deleting a file/directory

To delete a file or a directory we have to use delete() method. As stated in introductory paragraph if directory has data that data needs to be deleted first. "rm -rf *" does not work in java :).

    public void deleteDirectory(String path) {
        File file  = new File(path);
            String[] childFiles = file.list();
            if(childFiles == null) {
                //Directory is empty. Proceed for deletion
            else {
                //Directory has other files.
                //Need to delete them first
                for (String childFilePath :  childFiles) {
                    //recursive delete the files
        else {
            //it is a simple file. Proceed for deletion

Above method will delete complete directory.

1 comment:

  1. See here:
    You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

    FileUtils.deleteDirectory(new File("directory"));


t> UA-39527780-1 back to top