Java Path Delete nio optimisticDelete(Path path)

Here you can find the source of optimisticDelete(Path path)

Description

Delete a file (not recursively) and ignore any errors.

License

Apache License

Parameter

Parameter Description
path the path to delete

Declaration

public static void optimisticDelete(Path path) 

Method Source Code

//package com.java2s;
/*//from   w  w w .  j  a v  a 2  s .c  o  m
 * Copyright (C) 2012-present the original author or authors.
 *
 * 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 {
    /**
     * Delete a file (not recursively) and ignore any errors.
     *
     * @param path the path to delete
     */
    public static void optimisticDelete(Path path) {
        if (path == null) {
            return;
        }

        try {
            Files.delete(path);
        } catch (IOException ignored) {
        }
    }

    /**
     * Delete a file or recursively delete a folder, do not follow symlinks.
     *
     * @param path the file or folder to delete
     * @throws IOException if something goes wrong
     */
    public static void delete(Path path) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                if (!attrs.isSymbolicLink()) {
                    Files.delete(path);
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);

                return FileVisitResult.CONTINUE;
            }

        });
    }
}

Related

  1. deleteRecursively(Path path)
  2. deleteTmpDir(Path path)
  3. deleteTreeBelowPath(Path startHerePath)
  4. doDelete(@Nonnull Path path)
  5. forceDelete(Path path)
  6. readAndDelete(final Path p)
  7. recursiveDelete(Path directory)
  8. recursiveDelete(Path path)
  9. recursiveDelete(Path pathToBeDeleted)