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>
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()));