Java Directory Delete nio deleteFileOrFolder(final Path path)

Here you can find the source of deleteFileOrFolder(final Path path)

Description

delete File Or Folder

License

Apache License

Declaration

public static void deleteFileOrFolder(final Path path) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;

public class Main {
    public static void deleteFileOrFolder(final Path path) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override/* ww w .j a va  2s. c  o  m*/
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(final Path file, final IOException e) {
                return handleException(e);
            }

            private FileVisitResult handleException(final IOException e) {
                e.printStackTrace(); // replace with more robust error handling
                return TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException {
                if (e != null)
                    return handleException(e);
                Files.delete(dir);
                return CONTINUE;
            }
        });
    }
}

Related

  1. deleteDirOrFile(Path p, boolean followSymLinkDir)
  2. deleteDirReqursivelyIfExists(File dir)
  3. deleteDirWithFiles(File dir, int maxDepth)
  4. deleteFileOrDirectory(File file)
  5. deleteFileOrDirectory(final File source)