Java非递归方式获取目录及其子目录中的所有文件
我正在尝试获取目录及其子目录中所有文件的列表。我当前的递归方法如下:
private void printFiles(File dir) {
for (File child : dir.listFiles()) {
if (child.isDirectory()) {
printFiles(child);
} else if (child.isFile()) {
System.out.println(child.getPath());
}
}
}
printFiles(new File("somedir/somedir2"));
但是,我希望有一种非递归方法(可能是现有的 API 调用)来执行此操作。如果不是,这是最干净的方法吗?
I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:
private void printFiles(File dir) {
for (File child : dir.listFiles()) {
if (child.isDirectory()) {
printFiles(child);
} else if (child.isFile()) {
System.out.println(child.getPath());
}
}
}
printFiles(new File("somedir/somedir2"));
However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您始终可以使用堆栈(对于 DFS)或队列(对于 BFS)将递归解决方案替换为迭代解决方案:
You can always replace a recursive solution with an iterative one by using a stack (for DFS) or a Queue (For BFS):
从 Java 8 开始,您可以使用 Files#walk 递归列出给定目录中的所有文件和目录。此外,如果您只需要常规文件,您可以应用
Files::isRegularFile
之类的过滤器来过滤目录。另一方面,如果您只需要列出给定目录而不列出其子目录,则可以使用惰性方法 Files#list 只会为您提供给定目录中的文件和目录。您可以再次进一步应用上述过滤器。
Java 8 onward, you can use Files#walk to list out all files and directories recursively in a given directory. Further you can apply the filter like
Files::isRegularFile
to filter out the directories if you need only regular files.On the flip side, if you only need to list the given directory but not its sub-directories, you can use the lazy method Files#list which will only give you the files and directories in the given directory. You can again further apply the filter mentioned above.
FileUtils 可能是最好的方法去。 (链接问题的副本)
仅发布,以便搜索此内容的人会看到它,并且可能不会阅读评论
编辑:使用列表文件的方法
FileUtils Is probably the best way to go. (COPY OF THE LINKED QUESTION)
only posted so people searching this will see it and will probably not read the comments
edit: Methods to be used Listfiles