• How to delete folder with all files and sub folders in it using java 8.
  • We can use java 8 Stream to delete folder recursively 
  • Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  • .sorted(Comparator.reverseOrder())
  • .map(Path::toFile)
  • .peek(System.out::println)
  • .forEach(File::delete);

  1. Files.walk -  this method return all files/directories below the parent folder
  2. .sorted - sort the list in reverse order, so the folder itself comes after the including subfolders and files
  3. .map - map the file path to file
  4. .peek - points to processed entry
  5. .forEach - on every File object calls the .delete() method 




#1: Java Example program to delete folders and subfolders using java 8 stream

  1. package com.instanceofjava;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.FileVisitOption;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.util.Comparator;
  9. /**
  10.  * @author www.Instanceofjava.com
  11.  * @category interview questions
  12.  * 
  13.  * Description: delete folders and sub folders using java 8
  14.  *
  15.  */

  16. public class DeleteFolder {

  17. public static void main(String[] args) {
  18. Path rootPath = Paths.get("C:\\Users\\Saidesh kilaru\\Desktop\\folder1");
  19. try {
  20. Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  21.     .sorted(Comparator.reverseOrder())
  22.     .map(Path::toFile)
  23.     .peek(System.out::println)
  24.     .forEach(File::delete);
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }

  29. }

Output:

  1. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder\file2 in sub folder.docx
  2. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder
  3. C:\Users\Saidesh kilaru\Desktop\folder1\file1.docx
  4. C:\Users\Saidesh kilaru\Desktop\folder1



Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu