Java Path Delete nio deleteFilesRecursively(Path path, final PathMatcher pathMatcher)

Here you can find the source of deleteFilesRecursively(Path path, final PathMatcher pathMatcher)

Description

Deletes the files that match the PathMatcher.

License

Apache License

Exception

Parameter Description
IOException If it fails traversing or deleting the tree.

Declaration

public static int deleteFilesRecursively(Path path, final PathMatcher pathMatcher) throws IOException 

Method Source Code


//package com.java2s;
/*// w w  w. ja v  a 2 s. c o  m
 * Copyright (C) 2016 Google Inc.
 *
 * 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.PathMatcher;
import java.nio.file.SimpleFileVisitor;

import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    /**
     * Deletes the files that match the PathMatcher.
     *
     * <p> Note that this method doesn't delete the directories, only the files inside those
     * directories. This is fine for our use case since the majority of SCMs don't care about empty
     * directories.
     *
     * @throws IOException If it fails traversing or deleting the tree.
     */
    public static int deleteFilesRecursively(Path path, final PathMatcher pathMatcher) throws IOException {
        final AtomicInteger counter = new AtomicInteger();
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(file)) {
                    Files.delete(file);
                    counter.incrementAndGet();
                }
                return FileVisitResult.CONTINUE;
            }
        });
        return counter.get();
    }
}

Related

  1. deleteFile(Path path)
  2. deleteFile(String filePath)
  3. deleteFile(String path)
  4. deleteFilesIfExist(Path... files)
  5. deleteFilesIgnoringExceptions(final Path... files)
  6. deleteIfExists(Path thePath)
  7. deleteIfExists(Path value)
  8. deleteIndexBeforeStart(String basePath)
  9. deleteLockFile(Path logFile)