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 final boolean deleteDirectory(File directory) 

Method Source Code


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

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;

public class Main {
    public static final boolean deleteDirectory(File directory) {
        if (!directory.exists())
            return true;
        try {/*from   w  ww .j a  va  2s.  c  o  m*/
            // Try to delete the directory. We skip all the catch blocks if this directory
            // is able to be deleted, or if it's empty.
            Files.delete(directory.toPath());
        }

        // The directory wasn't empty, so we'll try to go through and delete its
        // contents recursively.
        catch (DirectoryNotEmptyException e) {
            // This is clearly a valid directory, so, if listFiles() returns false,
            // there was an IO error, which means we've failed. :(
            if (directory.listFiles() == null)
                return false;
            // We can now safely iterate over this directory's contents. :D
            for (File f : directory.listFiles()) {
                // If we fail to delete any subfiles/directories, then we can't delete this one,
                // so we return false.
                if (!deleteDirectory(f))
                    return false;
            }
            // An IOException occurred. Return false.
        } catch (IOException e) {
            return false;
        }
        // Everything went well. Return true.
        return true;
    }
}

Related

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