我试图使用更多的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);
或者你可以将方法参数扩展为一个lambda表达式,在 forEach
消耗法 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());
}});