我想知道是否有办法增强下面的代码,不仅匹配,还删除名称中包含“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);
}
}
答案 0 :(得分:0)
您可以使用apache commons库org.apache.commons.io.FileUtils删除文件/目录,因为此FileUtils.deleteQuitely()也允许删除非空目录。
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()));
}
}