Java Directory Delete nio deleteDirReqursivelyIfExists(File dir)

Here you can find the source of deleteDirReqursivelyIfExists(File dir)

Description

delete Dir Reqursively If Exists

License

Open Source License

Declaration

public static void deleteDirReqursivelyIfExists(File dir) throws IOException 

Method Source Code


//package com.java2s;
/*//from ww  w  .j a v a  2s.c  o m
 * Copyright (C) 2016 NAUMEN. All rights reserved.
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file LICENSE.GPL included in the
 * packaging of this file.
 *
 */

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.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void deleteDirReqursivelyIfExists(File dir) throws IOException {
        if (dir.exists()) {
            deleteDirReqursively(dir);
        }
    }

    public static void deleteDirReqursively(File dir) throws IOException {
        if (dir.isDirectory()) {
            Path directory = Paths.get(dir.getAbsolutePath());
            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. deleteDirectoryRecursively(Path path)
  2. deleteDirectorySelectively(Path path, Predicate predicate)
  3. deleteDirIfEmpty(Path dir)
  4. deleteDirIfExists(Path dirPath)
  5. deleteDirOrFile(Path p, boolean followSymLinkDir)
  6. deleteDirWithFiles(File dir, int maxDepth)
  7. deleteFileOrDirectory(File file)
  8. deleteFileOrDirectory(final File source)
  9. deleteFileOrFolder(final Path path)