Java Path Delete nio deleteTreeBelowPath(Path startHerePath)

Here you can find the source of deleteTreeBelowPath(Path startHerePath)

Description

Delete the whole file tree below the given path.

License

Apache License

Declaration

public static void deleteTreeBelowPath(Path startHerePath) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    /**/* w ww  . ja v  a2  s .com*/
     * Delete the whole file tree below the given path.  Files first while traversing, and the directories at the end.
     */
    public static void deleteTreeBelowPath(Path startHerePath) throws IOException {

        List<Path> dirPaths = new ArrayList<>();

        // Delete files as we see them.  Save directories for deletion later.

        Files.walk(startHerePath).forEach(path -> {
            if (Files.isDirectory(path)) {
                dirPaths.add(path);
            } else {
                try {
                    Files.delete(path);
                } catch (IOException e) {
                    e.printStackTrace(); // so we can continue even if a file is open.
                }
            }
        });

        Collections.sort(dirPaths);
        Collections.reverse(dirPaths);

        for (Path path : dirPaths) {
            try {
                Files.delete(path);
            } catch (IOException e) {
                System.out.println("Could not delete " + path + ": " + e); // better suggestions?
            }
        }
    }
}

Related

  1. deleteRecursive(Path path)
  2. deleteRecursively(final Path path)
  3. deleteRecursively(Path directory)
  4. deleteRecursively(Path path)
  5. deleteTmpDir(Path path)
  6. doDelete(@Nonnull Path path)
  7. forceDelete(Path path)
  8. optimisticDelete(Path path)
  9. readAndDelete(final Path p)