Java File Delete nio deleteFileRescursive(File file)

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

Description

delete File Rescursive

License

Open Source License

Declaration

public static boolean deleteFileRescursive(File file) 

Method Source Code


//package com.java2s;
/*/*from   w  w  w .j  a v a2 s . c  o  m*/
 * Copyright (c) 2018 Waritnan Sookbuntherng
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

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

public class Main {
    public static boolean deleteFileRescursive(File file) {
        return deleteFileRescursive(file, true);
    }

    public static boolean deleteFileRescursive(File file, boolean safeDelete) {
        String path = file.getAbsolutePath();
        if (safeDelete && (path.equals("/") || path.equals(System.getProperty("user.home")))) {
            throw new RuntimeException(
                    "Did you really trying to remove entire filesystem? or user's home directory?");
        }

        if (!file.exists()) {
            return true;
        }

        if (file.isFile() || Files.isSymbolicLink(file.toPath())) {
            return file.delete();
        }

        File[] files = file.listFiles();
        if (files == null) {
            return false;
        }

        for (File f : files) {
            if (!deleteFileRescursive(f)) {
                return false;
            }
        }

        return file.delete();
    }
}

Related

  1. deleteFile(File f)
  2. deleteFile(File f)
  3. deleteFile(String fileName)
  4. deleteFile(String filename)
  5. deleteFileCascade(String directory)
  6. deleteFiles(File directory, String affix)
  7. deleteIfEmpty(final File directory)
  8. deleteLocalFile(final String fileName)
  9. deleteLocalFileOrDirectory(File file)