Java Path Create nio clearAndCreate(Path dir)

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

Description

clear And Create

License

Open Source License

Declaration

public static void clearAndCreate(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 {
    public static void clearAndCreate(Path dir) throws IOException {
        //TODO:  check whether the Path is a dir
        if (Files.exists(dir)) {
            deleteDirectory(dir);/*  w  w w.j  av a2 s. c  o  m*/
        }
        Files.createDirectory(dir);
    }

    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);
                } 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. createACL(Path root, Path p, GroupPrincipal readOnly, GroupPrincipal readWrite)
  2. createAndGetOutputStream(String typename, String outputPath)
  3. createBufferedReader(Path path)
  4. createChecksums(final Path file, final Map functions)