How to Remove Directory in Java easily

Simple way to Delete a Folder in Java


One of the easiest ways to delete a folder is to apply a smart logic. When you have got it into an idea, you will have to immediately recall that it is 'repeat' what can make the things go. Well, if i want to delete a folder, then all i need to do is to delete all the files in it including the folders and finally the folder itself. Here i have written a simple method and also explained how-to delete a folder in Java.


import java.io.*;

class JavaDeleteAFolder
{
public static void main(String args[]) throws Exception
{
// Create a file pointing a folder
File f=new File("myfolder");

// Delete the folder
delete(f);
}
public static void delete(File file)
{

// Check if file is directory/folder
if(file.isDirectory())
{
// Get all files in the folder
File[] files=file.listFiles();

for(int i=0;i<files.length;i++)
{

// Delete each file in the folder
delete(files[i]);

}

// Delete the folder
file.delete();

}


else
{

// Delete the file if it is not a folder
file.delete();

}
}
}

delete(File file): This is what the method i have written. This method takes a file object.

What it does with the file object?

  • It checks whether the given file object points to a folder (directory) or just a normal file.
  • If the above condition is not satisfied, then the file is not a folder and is just a normal file.
What if the file is a directory?

  • List all the files in the directory using file.listFiles() which will return an array of all the files (including sub-folders) in the folder that the file object points out to.
  • Write a for-loop and then, call the delete(File file) method again. Again, this method checks if the file is a directory or not. If it is then things go from the starting of the above point. If it is just a normal file, then it will simply be deleted using the delete() method in the java.io.File
  • After all the files in the folder were deleted, delete the folder itself.