Java Path Delete nio recursiveDeleteOnShutdownHook(final Path path)

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

Description

recursive Delete On Shutdown Hook

License

Apache License

Declaration

public static void recursiveDeleteOnShutdownHook(final Path path) 

Method Source Code

//package com.java2s;
/*//w  w w. ja va 2  s.c  o m
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

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 {
    public static void recursiveDeleteOnShutdownHook(final Path path) {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                        @Override
                        public FileVisitResult visitFile(Path file,
                                @SuppressWarnings("unused") 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;
                            }
                            throw e;
                        }
                    });
                } catch (IOException e) {
                    throw new RuntimeException("Failed to delete " + path, e);
                }
            }
        }));
    }
}

Related

  1. readAndDelete(final Path p)
  2. recursiveDelete(Path directory)
  3. recursiveDelete(Path path)
  4. recursiveDelete(Path pathToBeDeleted)
  5. recursiveDeleteDirectory(Path dir)
  6. recursivelyDeleteFilesFromDir(Path aDirectory)
  7. recusiveDeleteIfExists(Path p)