java

How to delete a directory if exists in Java

In this tutorial, we are going to see how to delete a directory if exists in Java.

To delete a folder or directory, you can just use File.delete(), but the folder must be empty to delete it.

Sometimes, you may need to recursively delete a folder, which means all of its subdirectories and files should be deleted as well:
 

Java Program to delete a directory if exists
import java.io.*;

public class Main
{	
    public static void delete(File f) throws IOException{
 
    	if(f.isDirectory()){
    	  //if the directory is empty, delete it
    	  if(f.list().length == 0){
    	    f.delete();
    	    System.out.println("Directory is deleted: "+ f.getAbsolutePath());
    	  }else{
    	    //list the contents of the directory
    	    String files[] = f.list();
     
    	    for (String tmp : files) {
    	       File file = new File(f, tmp);
    	       //Delete recursively
    	       delete(file);
    	    }
    	    //check the directory again, if empty, delete it
    	    if(f.list().length == 0){
    	    f.delete();
    	    System.out.println("Directory is deleted: "+ f.getAbsolutePath());
    	    }
    	    }
    	}else{
    	    //if there is a file, delete it
    	    f.delete();
    	    System.out.println("File is deleted: " + f.getAbsolutePath());
    	}
    }

	public static void main(String[] args)
	{
		File dir = new File("C:\\test");
		try{
			delete(dir);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

Output:

Directory is deleted: C:\test\lib
File is deleted: C:\test\lib\jdom-2.3.0.jar
File is deleted: C:\test\lib\jdom-2.3.0-crontab.jar
File is deleted: C:\test\lib\jdom-2.3.0-jdbc.jar
File is deleted: C:\test\lib\jdom-2.3.0-telnet.jar
Directory is deleted: C:\test\lib\tmp
Directory is deleted: C:\test\lib\var
Directory is deleted: C:\test\lib\user
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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