Java Folder Delete nio deleteFolderAndSubfolders(Path pathToFile)

Here you can find the source of deleteFolderAndSubfolders(Path pathToFile)

Description

Delete folder and all subcontents.

License

Open Source License

Parameter

Parameter Description
pathToFile - Path to the file to be deleted

Declaration

public static void deleteFolderAndSubfolders(Path pathToFile) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.nio.file.Path;

import java.util.Stack;

public class Main {
    /**/*from w ww.  java2  s  .co  m*/
     * Delete folder and all subcontents. Avoids recursion so won't crash on deeply
     * nested folders. 
     * 
     * @param pathToFile - {@link Path} to the file to be deleted
     */
    public static void deleteFolderAndSubfolders(Path pathToFile) {
        File f = pathToFile.toFile();
        File[] currentFileList;
        Stack<File> stack = new Stack<>();
        stack.push(f);
        while (!stack.isEmpty()) {
            if (stack.lastElement().isDirectory()) {
                currentFileList = stack.lastElement().listFiles();
                if (currentFileList.length > 0) {
                    for (File curr : currentFileList)
                        stack.push(curr);

                } else
                    stack.pop().delete();

            } else
                stack.pop().delete();

        }
    }
}

Related

  1. delete(Path folder, List noDeleteFiles)
  2. deleteEmptyFolder(String... dirNames)
  3. deleteFile(String folderName, String fileName)
  4. deleteFolder(Path folder)
  5. deleteFolder(Path path)
  6. deleteRecursively(File folder)