Java File Delete nio deleteLocalFileOrDirectory(File file)

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

Description

Delete a local file or directory.

License

Open Source License

Parameter

Parameter Description
file file or directory to delete.

Exception

Parameter Description
Exception if there are any errors.

Declaration

public static void deleteLocalFileOrDirectory(File file) throws Exception 

Method Source Code


//package com.java2s;
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 {
    /**/* ww w .  ja v  a2  s  .  co  m*/
     * Delete a local file or directory.
     * Directories will be deleted recursively.
     *
     * @param file file or directory to delete.
     * @throws Exception if there are any errors.
     */
    public static void deleteLocalFileOrDirectory(File file) throws Exception {
        if (file.isFile()) {
            Files.delete(file.toPath());
        } else if (file.isDirectory()) {
            deleteLocalDirectory(file);
        }
    }

    /**
     * Recursively delete a local directory.
     *
     * @param directory the directory to delete.
     * @throws Exception if directory is not a directory, or if there are any errors.
     */
    public static void deleteLocalDirectory(File directory) throws Exception {
        if (!directory.isDirectory()) {
            throw new Exception("File " + directory.getAbsolutePath() + " is not a directory.");
        }
        Files.walkFileTree(directory.toPath(), 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 e) throws IOException {
                if (e == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed
                    throw e;
                }
            }
        });
    }
}

Related

  1. deleteFileCascade(String directory)
  2. deleteFileRescursive(File file)
  3. deleteFiles(File directory, String affix)
  4. deleteIfEmpty(final File directory)
  5. deleteLocalFile(final String fileName)
  6. deleteMatching(File baseFile, String regex)
  7. deletePidFile()
  8. deleteQuietly(File file)
  9. deleteRecursive(File fileOrDirectory)