- 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);
- Files.walk - this method return all files/directories below the parent folder
- .sorted - sort the list in reverse order, so the folder itself comes after the including subfolders and files
- .map - map the file path to file
- .peek - points to processed entry
- .forEach - on every File object calls the .delete() method
#1: Java Example program to delete folders and subfolders using java 8 stream
- package com.instanceofjava;
- import java.io.File;
- import java.io.IOException;
- import java.nio.file.FileVisitOption;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.Comparator;
- /**
- * @author www.Instanceofjava.com
- * @category interview questions
- *
- * Description: delete folders and sub folders using java 8
- *
- */
- public class DeleteFolder {
- public static void main(String[] args) {
- Path rootPath = Paths.get("C:\\Users\\Saidesh kilaru\\Desktop\\folder1");
- try {
- Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
- .sorted(Comparator.reverseOrder())
- .map(Path::toFile)
- .peek(System.out::println)
- .forEach(File::delete);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Output:
- C:\Users\Saidesh kilaru\Desktop\folder1\subfolder\file2 in sub folder.docx
- C:\Users\Saidesh kilaru\Desktop\folder1\subfolder
- C:\Users\Saidesh kilaru\Desktop\folder1\file1.docx
- C:\Users\Saidesh kilaru\Desktop\folder1
No comments