Delete a directory recursively in java 8

Let’s learn to delete a directory recursively in java 8.

Delete a directory recursively in java 8

In the below example we are using Files.walk(path) method to recursively delete specified directory and all its sub-directories.

Files.walk() method returns a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

Now let’s see java program.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
public class Java8DeleteDirectory
{
   public static void main(String[] args)
   {
      Path directory = Paths.get("B:\\New folder");
      Files.walk(directory)
      .sorted(Comparator.reverseOrder())
      .forEach(path -> {
          try 
          {
             System.out.println("Deleting directory: " + path);
             Files.delete(path);
          } 
          catch(IOException ex) 
          {
             ex.printStackTrace();
          }
       });     
   }
}


Also read – if else in java