Deletes a directory and its content recursively with NIO. - Java java.nio.file

Java examples for java.nio.file:Path

Description

Deletes a directory and its content recursively with NIO.

Demo Code


//package com.java2s;

import java.io.IOException;

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

public class Main {
    /**// w ww  .  j ava  2  s .  c om
     * Deletes a directory and its content recursively.
     */
    public static void deleteDirectory(Path directory) throws IOException {
        if (!Files.exists(directory)) {
            return;
        }

        cleanDirectory(directory);
        Files.delete(directory);
    }

    /**
     * Cleans the given directory without deleting it.
     */
    public static void cleanDirectory(Path directory) throws IOException {
        if (!Files.exists(directory)) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!Files.isDirectory(directory)) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        DirectoryStream<Path> directoryStream = Files
                .newDirectoryStream(directory);
        IOException exception = null;
        for (Path p : directoryStream) {
            try {
                delete(p);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }
        directoryStream.close();

        if (exception != null) {
            throw exception;
        }
    }

    /**
     * Deletes a file or directory. A directory does not have to be empty.
     */
    public static void delete(Path fileOrDirectory) throws IOException {
        if (Files.isDirectory(fileOrDirectory)) {
            deleteDirectory(fileOrDirectory);
        } else {
            Files.deleteIfExists(fileOrDirectory);
        }
    }
}

Related Tutorials