为什么我不能从这些代码中打印任何单词? Eclipse在“控制台”字段上未显示任何内容。
package test;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
public class Test2 {
public static void main(String[] args) {
PathMatcher matcher =
FileSystems.getDefault().getPathMatcher("glob:*.{java,class}");
Path filename = Paths.get("C:\\Users\\user\\eclipse-workspace\\test\\bin\\test");
if (matcher.matches(filename)) {
System.out.println(filename);
}
}
}
答案 0 :(得分:0)
您要匹配目录路径,而不是文件。如果要匹配单个文件路径,则可以执行以下操作:
PathMatcher matcher = FileSystems.getDefault()
.getPathMatcher("glob:**/*.{java,class}");
Path path = Paths.get("..", "classes", "MyClass.class");
if (matcher.matches(path)) {
System.out.println(path);
}
看看this answer,它显示了如何将匹配器与Files.walkFileTree()
一起使用来检查目录。或多或少以下内容:
PathMatcher matcher = FileSystems.getDefault()
.getPathMatcher("glob:**/*.{java,class}");
Path path = Paths.get("..", "classes");
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
...