【发布时间】:2023-03-28 10:55:02
【问题描述】:
我想仅列出 Java 8 中以 .txt 扩展名结尾的文件夹中的文件名。
通过这段代码,我得到了所有文件名,还有很多带有 .txt 扩展名的文件:
List<Path> fileNames = Files.list(configFilePath)
.map(Path::getFileName)
.sorted()
.collect(toList());
但是用这段代码我得到一个空的:
List<Path> fileNames = Files.list(configFilePath)
filter(file -> file.getFileName().endsWith(".txt"))
.map(Path::getFileName)
.sorted()
.collect(toList());
【问题讨论】:
-
PathAPI 真的很烦人,不仅像getFileName()这样的方法返回Path而不是名称String,而且还提供像endsWith(String)这样的方法,其语义完全不同比String.endsWith(String)。我不知道,我偶然发现它的频率。要点是,更改您的代码 as suggested by this answer 或使用file.getFileName().toString().endsWith(".txt")并记住此示例,说明当您必须设计 API 时如何不这样做。
标签: java lambda collections java-8