Java8 Stream of files, how to control the closing of files?

后端 未结 5 2104
陌清茗
陌清茗 2021-01-06 02:39

Suppose I have a Java8 Stream and that I use that stream to map and such, how can I control the closing of the FileReader

5条回答
  •  一整个雨季
    2021-01-06 03:12

    Perhaps a better solution is to use a Consumer to consume each element in the stream.

    Another problem you might be running into if there are a lot of files is the files will all be open at the same time. It might be better to close each one as soon as it's done.

    Let's say you change the code above into a method that takes a Consumer

    I probably wouldn't use a stream for this but we can use one anyway to show how one would use it.

    public void readAllFiles( Consumer consumer){
        Objects.requireNonNull(consumer);
    
        filenames.map(File::new)
                 .filter(File::exists)
                 .forEach(f->{
    
                     try(BufferedReader br = new BufferedReader(new FileReader(f))){
                         consumer.accept(br);
                     } catch(Exception e) {
                         //handle exception
                     }
                 });
    }
    

    This way we make sure we close each reader and can still support doing whatever the user wants.

    For example this would still work

     readAllFiles( br -> System.out.println( br.lines().count()));
    

提交回复
热议问题