Java Delete Directory

Hi everyone!! Welcome to flower brackets blog. In this post you are going to learn java delete directory.

java delete directory

In java, if we want to delete directory, compiler checks delete method of File class to check if directory is empty or not.

If it is empty, directory gets deleted. Else delete method will return false. So we have to recursively delete all the files. Now let’s see java program on how to delete directory/folder in java,

Example : how to delete directory in java

import java.io.*;

public class DeleteDirectoryExample
{
   public static void main(String[] args)
   {
      File dir = new File("B:/JavaExample");
		
      if(dir.isDirectory() == false) 
      {
         System.out.println("It's not a directory!!!");
         return;
      }
      File listFile[] = dir.listFiles();
      for(File file : listFile)
      {
         System.out.println("Deleting file : " + file.getName());
         file.delete();
      }
      // by now directory is empty.
      // so we are deleting directory
      System.out.println("Deleting Directory = " + dir.delete());
   }
}


Delete directories recursively in java

Before Java 7, to delete a directory with nested directories we had to write recursion based code. Now in java 7 we have File class to delete nested directories.

Also Read – Create Directory Java Program

Let’s see how to delete directory in java using recursion,

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class DeleteRecursiveDemo 
{
   public static void main(String[] args) throws IOException 
   {
      Path dir = Paths.get("B:/JavaExample");
      Files.walkFileTree(dir, new SimpleFileVisitor<Path>() 
      {
         @Override
         public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException 
         {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
         }

         @Override
         public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException 
         {				
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
         }
      });
   }
}


 

Conclusion

That’s it guys. In this post we learnt how to delete a directory with files in java. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Related Posts