0

I am wondering if there is a way to enhance the code below and not only match but also delete all files and directories that contain the "e" character in their name. Any help is appreciated!

Thank you in advance.

Here is the code:

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);
    }
}
elena nincevic
  • 83
  • 1
  • 1
  • 10
  • How about getting the filenames as String and use a `contains(String keyword)` to detect the files that contains your keyword and keeping them in a String List and deleting the list immediately? – cihan adil seven May 17 '16 at 12:57
  • What to do if a directory name match your criteria. Should it be deleted recursively? – SubOptimal May 17 '16 at 14:24
  • @SubOptimal if the directory or file name match the criteria, meaning they contain "e" in their name, they should be removed/deleted. – elena nincevic May 17 '16 at 16:30

1 Answers1

0

You could use apache commons library org.apache.commons.io.FileUtils to delete files/directory as this FileUtils.deleteQuitely() allows to delete non empty dirs as well.

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

something like below:

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()));
    }
}
Vijay
  • 542
  • 4
  • 15