我正在尝试过滤文件夹“C://Temp”中以“EMP”开头的文件,并尝试返回我在下面的代码中尝试过的“路径”列表,但它始终返回空列表。我正在做的事情有语法错误吗?
String directoryPath = "C://Temp";
String partOfFileName = "EMP";
List<Path> fileNames = Files.list(Paths.get(directoryPath))
.filter(line -> line.toString().startsWith(partOfFileName))
.map(Path::getFileName)
.collect(Collectors.toList());
最佳答案
由于您正在检查完整路径,因此您可能需要使用“endsWith”而不是“startsWith”直接检查立即数。
现在,如果您位于“folder1/folder2/test”中并且使用startsWith,它将检查并尝试过滤第一个目录“folder1”。
try {
List<Path> fileNames = Files.list(Paths.get(directoryPath))
.filter(line -> line.endsWith(partOfFileName))
.map(Path::getFileName)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
关于java 8 路径过滤器文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276768/