我正在使用FileVisitor对象递归地遍历一个文件目录。我确实重写了preVisitDirectory方法,但我希望将它的dir参数分配给位于此重写方法和FileVisitor对象的外部作用域中的字符串。这是我的密码:
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();
}它显然给了我一个关于“封闭作用域”的编译错误,我理解为什么会发生这种情况,但是我不知道怎么做,如何为每个目录分配子目录的名称?
我的最终目标是将我在此过程中找到的所有.txt文件的内容写入一些String。
发布于 2022-11-22 12:01:11
如果您想要返回所有文件中所有内容的连接,那么您可能更好地使用来自Files.walk的流。由此,您可以收集所有行,并允许您有机会过滤文件名和行,从而可能提供其他转换。
try (var walker = Files.walk(Path.of(System.getProperty("user.home") + "/UTP8dir"))) {
var contents = walker
.filter(Files::isRegularFile)
.flatMap(f -> {
try {
return Files.lines(f);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
})
.collect(joining("\n"));
}过去,我在这方面做过很多性能特性的测试,请参阅这个问题和这个带有测试的Github项目。
https://stackoverflow.com/questions/74525485
复制相似问题