Java 8:从文件夹/子文件夹中获取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48563709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 : Get files from folder / subfolder
提问by Nu?ito de la Calzada
I have this folders inside the resources folder of a SpringBootapp.
我在SpringBoot应用程序的资源文件夹中有这个文件夹。
resources/files/a.txt
resources/files/b/b1.txt
resources/files/b/b2.txt
resources/files/c/c1.txt
resources/files/c/c2.txt
I want to get all the txt file, so this is my code:
我想得到所有的txt文件,所以这是我的代码:
ClassLoader classLoader = this.getClass().getClassLoader();
Path configFilePath = Paths.get(classLoader.getResource("files").toURI());
List<Path> atrackFileNames = Files.list(configFilePath)
.filter(s -> s.toString().endsWith(".txt"))
.map(Path::getFileName)
.sorted()
.collect(toList());
But I only get the file a.txt
但我只得到文件a.txt
采纳答案by Eugene
Path configFilePath = FileSystems.getDefault()
.getPath("C:\Users\sharmaat\Desktop\issue\stores");
List<Path> fileWithName = Files.walk(configFilePath)
.filter(s -> s.toString().endsWith(".java"))
.map(Path::getFileName).sorted().collect(Collectors.toList());
for (Path name : fileWithName) {
// printing the name of file in every sub folder
System.out.println(name);
}
回答by Dumbo
Files.list(path)
method returns only stream of files in directory. And the method listing is not recursive.
Instead of that you should use Files.walk(path)
. This method walks through all file tree rooted at a given starting directory.
More about it:
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-
Files.list(path)
方法只返回目录中的文件流。并且方法列表不是递归的。
相反,您应该使用Files.walk(path)
. 此方法遍历以给定起始目录为根的所有文件树。
更多相关信息:https:
//docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption。 ..-