Java Directory Delete nio deleteDirectory(File directory)

Here you can find the source of deleteDirectory(File directory)

Description

delete Directory

License

Open Source License

Declaration

public static boolean deleteDirectory(File directory) 

Method Source Code


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

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;

import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static boolean deleteDirectory(File directory) {
        checkNotNull(directory);/*from  w w  w  .j  ava  2s.c o m*/
        checkArgument(directory.isDirectory(), "File is not directory.");

        try {
            Files.walkFileTree(directory.toPath(), new SimpleFileVisitor<Path>() {
                @Nonnull
                @Override
                public FileVisitResult visitFile(@Nonnull Path file, @Nonnull BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Nonnull
                @Override
                public FileVisitResult postVisitDirectory(@Nonnull Path dir, IOException exc) throws IOException {
                    if (exc == null) {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    } else {
                        throw exc;
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

Related

  1. deleteDir(String path)
  2. deleteDirectory(File dir)
  3. deleteDirectory(File dir)
  4. deleteDirectory(File directory)
  5. deleteDirectory(File directory)
  6. deleteDirectory(File directory)
  7. deleteDirectory(File directory)
  8. deleteDirectory(File file)
  9. deleteDirectory(File path)