gpt4 book ai didi

java - 是否可以通过.forEach方法列出文件特征?

转载 作者:行者123 更新时间:2023-12-01 14:27:14 24 4
gpt4 key购买 nike

我正在尝试使用更多的Java 8语法。我这里有一个简单的用例,以递归方式列出文件,在这里我想打印的不仅仅是文件名,如示例所示:

public void listFiles(String path) {
try {
Files.walk(Paths.get(path))
.filter(p -> {
return Files.isRegularFile(p);
})
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}

有没有一种方法可以通过forEach方法调用方法,将有问题的文件作为参数传递?我将如何引用该文件?

编辑:关于是否可以将每个要打印的文件的路径作为变量传递给另一种方法的讨论中有些困惑。

可以确认。这是代码:
 public void listFiles(String path) {
try {
Files.walk(Paths.get(path))
.filter(p -> {
return Files.isRegularFile(p);
})
.forEach(p -> myMethod(p));
} catch (IOException e) {
e.printStackTrace();
}
}

private void myMethod(Path path) {
System.out.println(path.toAbsolutePath());
try {
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
FileTime fileTime = attr.lastModifiedTime();
System.out.println("file date: " + fileTime);
} catch (IOException ex) {
// handle exception
}
}

最佳答案

只要您只关心通过管道传递的一个参数,就可以使用map方法。

Files.walk(Paths.get(path))
.filter(p -> Files.isRegularFile(p))
.map(Path::getFileName)
.forEach(System.out::println);

或者,您可以在 forEach方法内将方法参数扩展为lambda表达式,从而消耗通过过滤器的整个 Path(是常规文件):
Files.walk(Paths.get(path))
.filter(p -> Files.isRegularFile(p))
.forEach(p -> System.out.println("Path fileName: " + p.getFileName()));

为避免混淆,只能在 p / filter方法参数的范围内访问变量 forEach,即。 lambda表达式。请参阅最后一个片段扩展:
Files.walk(Paths.get(""))
.filter(path1 -> Files.isRegularFile(path1))
.forEach(new Consumer<Path>() {
@Override
public void accept(final Path p) {
// here is the `p`. It lives only in the scope of this method
System.out.println("Path fileName: " + p.getFileName());
}});

关于java - 是否可以通过.forEach方法列出文件特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61962701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com