Java Directory Delete nio deleteDirectory(Path dir)

Here you can find the source of deleteDirectory(Path dir)

Description

delete Directory

License

Open Source License

Declaration

private static boolean deleteDirectory(Path dir) throws IOException 

Method Source Code


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

import java.nio.file.Files;
import java.nio.file.Path;

import java.nio.file.DirectoryNotEmptyException;

import java.io.IOException;

public class Main {
    private static boolean deleteDirectory(Path dir) throws IOException {

        if (Files.isDirectory(dir)) {
            // let's get the children of the directory. Note, here there might be
            // files as well as other directories
            Path[] children = Files.list(dir).toArray(size -> new Path[size]);

            for (Path p : children) {
                try {
                    // if the directory that we try to delete is not empty,
                    // a DirectoryNotEmptyException is thrown, if that's the case,
                    // we return false
                    deleteDirectory(p);//ww  w  .j av a 2  s .co m
                } catch (DirectoryNotEmptyException e) {
                    return false;
                }
            }
        }

        // either file or an empty directory
        System.out.println("removing file or directory : " + dir);

        Files.delete(dir);
        // yeah, we deleted the file
        return true;
    }
}

Related

  1. deleteDirectory(File directory)
  2. deleteDirectory(File file)
  3. deleteDirectory(File path)
  4. deleteDirectory(final File directory)
  5. deleteDirectory(final Path dir, final int maxDepth)
  6. deleteDirectory(Path directory)
  7. deleteDirectory(Path directory)
  8. deleteDirectory(Path directory)
  9. deleteDirectory(Path directory)