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>
I know this is an old question, but there is a very nice solution that I found here and I don't think it's on SO.
The java.nio.file
offers methods that let you do this cleanly:
filenames.map(Paths::get)
// Nicer alternative to File::exists
.filter(Files::exists)
// This will automatically close the stream after each file is done reading
.flatMap(path -> {
try {
return Files.lines(path);
} catch (IOException e) {
// Seamlessly handles error opening file, no need for filtering
return Stream.empty();
}
})
.map(/* Do something with each line... */)