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>
Just for the sake of the argument ( though I agree with Louis above ) :
You can pass around the original Reader/InputStream ( or any object, but the case you provided is actually flawed programming, because you can pass the FileReader instead of encapsulating it with BufferedReader) using common-lang3 Pair Class. Jool is also a valid library that provides Tuple* classes.
Example :
filenames.map(File::new)
.filter(File::exists)
.map(f->{
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(f)
br = new BufferedReader(fr);
return Optional.of(Pair.of(br,fr)) ;
} catch(Exception e) {}
return Optional.ofNullable(br);
})
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap( pair -> {
try {
// do something with br
} finally {
try {
pair.getRight().close();
} catch (IOException x ){
throw new RuntimeException(x) ;
}
}
})