How do I iterate through the files in a directory in Java?

前端 未结 10 2084
星月不相逢
星月不相逢 2020-11-22 08:37

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

10条回答
  •  伪装坚强ぢ
    2020-11-22 09:21

    I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

    1. handle the case of empty directory
    2. Laziness

    but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

        File directoryFile = new File("put your path here");
        Stream files = Optional.ofNullable(directoryFile// directoryFile
                                                              .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                     .stream()
                                     .flatMap(Arrays::stream);// flatmap from Stream to Stream
    

提交回复
热议问题