Java File Delete nio recursiveDelete(File parent)

Here you can find the source of recursiveDelete(File parent)

Description

recursive Delete

License

Open Source License

Parameter

Parameter Description
parent a parameter

Return

boolean

Declaration

static public final boolean recursiveDelete(File parent) 

Method Source Code


//package com.java2s;
/*-/*from   ww w. j ava2s  .c  o  m*/
 *******************************************************************************
 * Copyright (c) 2011, 2015 Diamond Light Source Ltd.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Matthew Gerring - initial API and implementation and/or initial documentation
 *******************************************************************************/

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 {
    /**
     * @param parent
     * @return boolean
     */
    static public final boolean recursiveDelete(File parent) {

        if (parent.exists()) {
            if (parent.isDirectory()) {

                File[] files = parent.listFiles();
                for (int ifile = 0; ifile < files.length; ++ifile) {
                    if (files[ifile].isDirectory()) {
                        recursiveDelete(files[ifile]);
                    }
                    if (files[ifile].exists()) {
                        files[ifile].delete();
                    }
                }
            }
            return parent.delete();
        }
        return false;
    }

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

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

        });
    }
}

Related

  1. forceDelete(File file)
  2. forceDelete(File file)
  3. forceDelete(final File file)
  4. forceDeletion(File fileToDelete)
  5. recDeleteDirFile(File f)
  6. safeDeleteFile(final String fileName)
  7. secureDelete(File file)