我已经搜索过,但似乎无法弄清楚如何编写java代码,该代码将包含通配符(星号)的字符串作为输入,并输出解析了通配符的字符串。
我有一种特殊情况,我知道有 1 个或 0 个匹配的文件规范,因此我希望返回的字符串要么是有效的文件规范,要么为 null。
我已经获得了一些使用 Files.walkFileTree() 工作的示例代码,但它并不完全符合我的要求。我想将解析的文件名作为字符串返回,以便我可以在后续代码中使用...
我只是想向一些代码传递一个包含星号的字符串文件名
e.g.: input this String: filename*.tr
并返回一个字符串,其中星号解析为第一个匹配的文件名(或 null):
e.g.: get back this String: filename_201402041230.tr
这些文件所在的目录包含数千个文件,因此迭代目录中的所有文件并自己解析名称并不是一个有吸引力的选择。
任何帮助或指示将不胜感激。
为我的爆发道歉...感谢您的提示...这是我之前尝试过的: 然而,正如我所说,这不是我想要的,但它是我从研究中所能得到的最接近的结果。
Path startDir = Paths.get("C:\\huge_dir");
String pattern = "filename*.tr";
FileSystem fs = FileSystems.getDefault();
final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern);
FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>()
{
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attribs)
{
Path name = file.getFileName();
if (matcher.matches(name))
System.out.println(file);
return FileVisitResult.TERMINATE;
}
};
try
{
Files.walkFileTree(startDir, matcherVisitor);
}
catch (Exception e){System.out.println(e);}
最佳答案
您可以使用 nio2 Files.newDirectoryStream
带有附加模式匹配器的方法,仅列出与模式匹配的文件。由于您的字符串已经是 glob
模式,因此您可以将其作为第二个参数传递:
String pattern = "filename*.tr"
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, pattern)) {
//iterate over all matching files
List<Path> paths = new ArrayList<>();
for (Path path : ds) {
paths.add(path);
}
if (paths.isEmpty()) {
//no file found
} else if (paths.size() == 1) {
//found one result
Path result = paths.get(0) //now do whatever
} else {
//more than one match - probably an error in your case?
}
}
关于java - 如何使用 Java 7 解析通配 rune 件规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179048/