[英]SimpleFileVisitor to walk a directory tree to find all .txt files except in two sub directories
我想遍歷具有許多子目錄的目錄樹。 我的目標是打印除 subdir 和 anotherdir 子目錄中的所有 .txt 文件之外的所有 .txt 文件。 我可以使用以下代碼實現這一點。
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Users\\bhapanda\\Documents\\target");
Files.walkFileTree(path, new Search());
}
private static final class Search extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");
PathMatcher pm1 = FileSystems.getDefault().getPathMatcher("glob:**\\anotherdir");
if (pm.matches(dir) || pm1.matches(dir)) {
System.out.println("matching dir found. skipping it");
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:*.txt");
if (pm.matches(file.getFileName())) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
}
但是當我嘗試使用以下代碼組合 pm 和 pm1 PathMatchers 時,它不起作用。
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");
if (pm.matches(dir)) {
System.out.println("matching dir found. skipping it");
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
glob 語法有什么問題嗎?
是的,glob 語法有問題。 您需要將每個反斜杠加倍,以便它們在您的 glob 模式中保持轉義反斜杠。
第一個匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");
與以\\subdir
結尾的路徑不匹配。 相反,雙斜杠在 glob 模式中變成了單斜杠,這意味着 's' 正在被轉義。 由於轉義的 's' 只是一個 's',這個匹配器相當於:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**subdir");
這意味着它將匹配以subdir
結尾的任何路徑。 所以它將匹配路徑xxx\\subdir
,但也會匹配路徑xxx\\xxxsubdir
和xxxsubdir
。
組合匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");
有同樣的問題。 在這種情況下被轉義的是'{'。 在 glob 模式中,這意味着將 '{' 視為文字字符而不是模式組的開頭。 所以這個匹配器不會匹配路徑xxx\\subdir
,但它會匹配路徑xxx{subdir,anotherdir}
。
這兩個匹配器將執行預期的操作:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\subdir");
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\{subdir,anotherdir}");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.