Delete a directory recursively in java 8

Let’s learn 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 which 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.nio.file.Paths;
import java.util.Comparator;
public class Java8DeleteDirectory
{
   public static void main(String[] args) throws IOException
   {
      Path directory = Paths.get("A:/java/directory");
      Files.walk(directory)
          .sorted(Comparator.reverseOrder())
          .map(Path::toFile)
          .forEach(File::delete);
   }
}

Also read – if else in java