Java 需要在FileNameFilter接口的lambda表达式中构造文件实例
假设我的测试有以下目录结构Java 需要在FileNameFilter接口的lambda表达式中构造文件实例,java,lambda,functional-programming,Java,Lambda,Functional Programming,假设我的测试有以下目录结构 test | | ---test1 | | ---test2 | | ---random.txt 在这种结构中,test1和test2是目录,而random.txt是常规文件 我想写一个函数,给我一个给定文件路径的所有子目录的列表 尝试1,有效(无lambda表达式) 这个结果现在包含random.txt作为目录,但显然不是这样。为什么lambda函数会给出不同的结果 编辑: 仅在lambda表达式中创建文件实例时有效: return pathname.list((
test
|
|
---test1
|
|
---test2
|
|
---random.txt
在这种结构中,test1和test2是目录,而random.txt是常规文件
我想写一个函数,给我一个给定文件路径的所有子目录的列表
尝试1,有效(无lambda表达式)
这个结果现在包含random.txt作为目录,但显然不是这样。为什么lambda函数会给出不同的结果
编辑:
仅在lambda表达式中创建文件实例时有效:
return pathname.list((dir, name) -> new File(dir, name).isDirectory());
dir已经是一个文件对象了,但是为什么我们要从现有的文件实例创建一个文件实例呢
编辑2:
查看文档后,
dir
参数总是指找到文件的目录。这就是为什么random.txt
作为目录名返回的原因。但是我仍然不知道为什么需要创建一个新的文件实例。与您现有的尝试类似:
private static List<String> subDirectories(File pathname) {
return Arrays.stream(pathname.listFiles())
.filter(File::isDirectory)
.map(File::getName)
.collect(Collectors.toList());
}
正如您所知,test
是一个目录,这就是为什么random.txt
被过滤以输出的原因
编辑:使用
return pathname.list((dir, name) -> new File(dir, name).isDirectory());
从那时起,您创建了一个文件,而不是名为random.txt
的目录。其不是目录的原因在
如果parent是空的抽象路径名,则新文件实例为
通过将子级转换为抽象路径名并解析
与系统相关的默认目录的结果
在您的情况下,它不成立,因为父目录存在。在您的函数中
private static String[] subDirectories(File pathname) {
return pathname.list((dir, name) -> dir.isDirectory());
}
第一个参数dir
是基本目录,name
是必须测试为目录的实际文件元素。你可以用
private static List<String> subDirectories(File pathname) {
return Arrays.stream(pathname.listFiles())
.filter(File::isDirectory)
.map(File::getName)
.collect(Collectors.toList());
}
私有静态列表子目录(文件路径名){
返回Arrays.stream(路径名.listFiles())
.filter(文件::isDirectory)
.map(文件::getName)
.collect(Collectors.toList());
}
请注意,pathname.listFiles()
在存在时将返回null
没有文件,Arrays.stream(pathname.listFiles())
将抛出
在那种情况下是NPE
哦,这是一个很好的解决方案。“我还没有学习到关于流的知识,但我会记住这一点,以备将来参考。@MutatingAlgorithm更新了问题中相应的编辑。”。一般来说,尽量不要过多地修改问题。
return pathname.list((dir, name) -> new File(dir, name).isDirectory());
private static String[] subDirectories(File pathname) {
return pathname.list((dir, name) -> dir.isDirectory());
}
private static List<String> subDirectories(File pathname) {
return Arrays.stream(pathname.listFiles())
.filter(File::isDirectory)
.map(File::getName)
.collect(Collectors.toList());
}