Java Directory Delete nio deleteDirectory(File file)

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

Description

Method to delete entire directories recursively.

License

Open Source License

Parameter

Parameter Description
file a parameter

Return

True on success

Declaration

public static Boolean deleteDirectory(File file) 

Method Source Code

//package com.java2s;
/**//from  ww w . j a v  a2s.  c om
 * Small utility class created to do tasks that occur often.
 * 
 * @author Emil Carlsson
 * 
 * This file is a part of Doris
 *
 * Doris is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * Doris is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License 
 * along with Doris.  
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

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

public class Main {
    /**
     * Method to delete entire directories recursively.
     * @param file
     * @return True on success
     */
    public static Boolean deleteDirectory(File file) {

        file.setWritable(true, false);
        file.setExecutable(true, false);
        file.setReadable(true, false);
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                deleteDirectory(f);
            }
        }
        System.gc();

        Boolean deleted = file.delete();
        ;

        if (!deleted) {
            Path path = file.toPath();

            try {
                Files.deleteIfExists(path);
            } catch (Exception e) {
                if (file.isFile()) {
                    System.out.format("Deletion failed.\nManual deletion of %s needed.\n", file.getAbsolutePath());
                }
            }

        }

        return deleted;
    }
}

Related

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