I'm going through a file directory recursively using a FileVisitor
object. I did override the preVisitDirectory
method, but I want to assign its dir
parameter to a String which is located in the outer scope of this overridden method and FileVisitor
object. This is my code:
FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
String cur_dir = "";
FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs)
throws IOException {
// System.out.println("DIRECTORY NAME:"+ dir.getFileName()
// + " LOCATION:"+ dir.toFile().getPath());
cur_dir = dir.toFile().getPath();
System.out.println("cur_dir: " + cur_dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path visitedFile,BasicFileAttributes fileAttributes)
throws IOException {
System.out.println("FILE NAME: "+ visitedFile.getFileName());
return FileVisitResult.CONTINUE;
}
};
FileSystem fileSystem = FileSystems.getDefault();
String path = System.getProperty("user.home")+"/UTP8dir";
Path rootPath = fileSystem.getPath(path);
try {
Files.walkFileTree(rootPath, simpleFileVisitor);
} catch (IOException ioe) {
ioe.printStackTrace();
}
It obviously gives me a compilation error about "enclosing scope", I understand why this happens, but I don't know what's the way to do it though, how can I assign subdirectories's names to an outer-scope String for each directory?
My ultimate goal is to write the contents of all .txt files I find during this to some String
.