Java Directory Delete nio deleteDir(final File targetDir)

Here you can find the source of deleteDir(final File targetDir)

Description

Elimina un directorio con todo su contenido.

License

Apache License

Parameter

Parameter Description
targetDir Directorio a eliminar.

Declaration

static void deleteDir(final File targetDir) 

Method Source Code

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

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;
import java.util.logging.Logger;

public class Main {
    private static final Logger LOGGER = Logger.getLogger("es.gob.afirma");

    /** Elimina un directorio con todo su contenido.
     * @param targetDir Directorio a eliminar. */
    static void deleteDir(final File targetDir) {
        try {/*from   w ww. jav  a  2 s. c om*/
            Files.walkFileTree(targetDir.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException {
                    if (e != null) {
                        throw e;
                    }
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (final Exception e) {
            LOGGER.warning("No se pudo borrar el directorio '" + targetDir.getAbsolutePath() + "': " + e); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}

Related

  1. deleteDir(File dir)
  2. deleteDir(File file)
  3. deleteDir(String dirName)
  4. deleteDir(String path)
  5. deleteDirectory(File dir)
  6. deleteDirectory(File dir)