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

后端 未结 5 2132
陌清茗
陌清茗 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条回答
  •  Happy的楠姐
    2021-01-06 03:11

    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... */)
    

提交回复
热议问题