If I have the following code to walk through a directory and want to find a specific file.
The following works:
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) {}
But if I want to store only a single file variable instead of adding it to a list, it fails to compile.
The following code generates the message "Local variable filePath defined in an enclosing scope must be final or effectively final"
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) {}
What am I missing as to why the reference can't be copied to filePath? Is there a solution to store just the single file Path?