Non-recursive way to get all files in a directory and its subdirectories in Java

前端 未结 3 2165
温柔的废话
温柔的废话 2020-12-14 10:55

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)          


        
3条回答
  •  天命终不由人
    2020-12-14 11:21

    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.

提交回复
热议问题