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

后端 未结 5 2142
陌清茗
陌清茗 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:23

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

提交回复
热议问题