Как удалить все файлы, основываясь на определенном символе в именах файлов, используя Java

Мне интересно, есть ли способ улучшить приведенный ниже код и не только сопоставить, но и удалить все файлы и каталоги, содержащие в своем имени символ "e". Любая помощь приветствуется!

Заранее спасибо.

Вот код:

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

class Finder extends SimpleFileVisitor<Path> {
    private final PathMatcher matcher;
    Finder() {
        matcher = FileSystems.getDefault().getPathMatcher("glob:*e*");
    }

    //@Override 
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        find(file);
        return FileVisitResult.CONTINUE;
    }

    //@Override 
    public FileVisitResult preVisitDirectory(Path file, BasicFileAttributes attrs) {
        find(file);
        return FileVisitResult.CONTINUE;
    }

    void find(Path file) {
        Path name = file.getFileName();
        if(matcher.matches(name)) {
            System.out.println("Matched file: " + file.getFileName());
        }
    }
}

public class FileVisitor2 {
    public static void main(String[] args) throws IOException {
        Finder finder = new Finder();
        Path p = Paths.get("C:\\Users\\El\\School\\DirMain");
        Files.walkFileTree(p, finder);
    }
}

1 ответ

Вы можете использовать библиотеку apache commons org.apache.commons.io.FileUtils для удаления файлов / каталогов, так как этот FileUtils.deleteQuately() также позволяет удалять не пустые каталоги.

 FileUtils.deleteQuietly(new File(path.toUri()));

что-то вроде ниже:

void find(Path file) {
    Path name = file.getFileName();
    if(matcher.matches(name)) {
        System.out.println("Matched file: " + file.getFileName());
        FileUtils.deleteQuietly(new File(file.toUri()));
    }
}
Другие вопросы по тегам