使用 PathMatcher 获取特定扩展名的文件
Getting files of certain extension using PathMatcher
我想从一个目录(而不是它的子目录)中获取所有 *.pdf 文件。我使用 FileSystems.getDefault().getPathMatcher( "glob:**.pdf")
,但它是递归工作的。
编辑
我已经尝试过 FileSystems.getDefault().getPathMatcher( "glob:*.pdf")
但这没有给我任何文件(但给定目录中有 *.pdf 文件)。
问题在于使用 glob patterns
。
使用 FileSystems.getDefault().getPathMatcher( "glob:*.pdf")
而不是 FileSystems.getDefault().getPathMatcher( "glob:**.pdf")
。
以下摘自Javadoc:
The following rules are used to interpret glob patterns:
- The * character matches zero or more characters of a name component without crossing directory boundaries.
- The ** characters matches zero or more characters crossing directory boundaries.
来自文档:
*.java
Matches a path that represents a file name ending in .java
因此 glob:*.java
的路径匹配器仅 return 对实际文件名(例如 x.pdf
)为真,这些文件名由 Path.getFileName() 编辑 return例如。
在没有子目录的目录中迭代 PDF 文件的问题的可能解决方案可能是限制文件树遍历的深度,而不是更改匹配器的行为。
Path start = Paths.get("C:/Users/maxim/Desktop/test/");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");
Files.walk(start, 1)
.filter(matcher::matches)
.forEach(System.out::println);
我想从一个目录(而不是它的子目录)中获取所有 *.pdf 文件。我使用 FileSystems.getDefault().getPathMatcher( "glob:**.pdf")
,但它是递归工作的。
编辑
我已经尝试过 FileSystems.getDefault().getPathMatcher( "glob:*.pdf")
但这没有给我任何文件(但给定目录中有 *.pdf 文件)。
问题在于使用 glob patterns
。
使用 FileSystems.getDefault().getPathMatcher( "glob:*.pdf")
而不是 FileSystems.getDefault().getPathMatcher( "glob:**.pdf")
。
以下摘自Javadoc:
The following rules are used to interpret glob patterns:
- The * character matches zero or more characters of a name component without crossing directory boundaries.
- The ** characters matches zero or more characters crossing directory boundaries.
来自文档:
*.java
Matches a path that represents a file name ending in .java
因此 glob:*.java
的路径匹配器仅 return 对实际文件名(例如 x.pdf
)为真,这些文件名由 Path.getFileName() 编辑 return例如。
在没有子目录的目录中迭代 PDF 文件的问题的可能解决方案可能是限制文件树遍历的深度,而不是更改匹配器的行为。
Path start = Paths.get("C:/Users/maxim/Desktop/test/");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");
Files.walk(start, 1)
.filter(matcher::matches)
.forEach(System.out::println);