我注意到该listFiles()
方法返回文件以及目录,但是我只想filePath
用文件填充数组。我知道有一种isFile()
方法,但我不知道如何将其与listFiles()
实现我想要的方法结合起来。
我发现了一些类似的问题,但它们与在扩展名上应用过滤器有关,而我没有特别的文件扩展名。
提前致谢!:)
示例代码:
File f = new File (path);
File [] filePath;
filePath = f.listFiles(); // how to modify this to get files only?
使用File
API:
File f = new File (path);
File [] files = f.listFiles(File::isFile);
使用Path
设计得更好的API,您可以编写:
Path dir = Paths.get(path);
List<Path> path =
Files.list(dir)
.filter(Files::isRegularFile)
.collect(Collectors.toList());
或直接使用以下流Path
:
Path dir = Paths.get(path);
Files.list(dir)
.filter(Files::isRegularFile)
.forEach(p -> doSomethingWithP);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句