如果我有以下代码来浏览目录并想要查找特定文件。
以下作品:
List<Path> foundPaths = new ArrayList<Path>();
PathMatcher pathMatcher = "regex:.*somefile.exe";
Path downloadLocation = Paths.get("C:\Downloads");
try {
Files.walkFileTree(downloadLocation, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(file)) {
foundPaths.add(file);
}
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {}
但是,如果我只想存储单个文件变量而不是将其添加到列表中,则无法编译。
以下代码生成消息“在封闭范围内定义的本地变量filePath必须是最终的或有效的最终版本”
Path filePath = null;
PathMatcher pathMatcher = "regex:.*somefile.exe";
Path downloadLocation = Paths.get("C:\Downloads");
try {
Files.walkFileTree(downloadLocation, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (pathMatcher.matches(file)) {
filePath = file;
}
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {}
为什么无法将引用复制到filePath,我缺少什么?是否存在仅存储单个文件路径的解决方案?