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

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

    So, if you only have non-binary files you could use something like this:

    List fileNames = Arrays.asList(
                "C:\\Users\\wowse\\hallo.txt",
                "C:\\Users\\wowse\\bye.txt");
    
    fileNames.stream()
                .map(Paths::get)
                .filter(Files::exists)
                .flatMap(path -> {
                    try {
                        return Files.lines(path);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .forEach(System.out::println);
    

    If you have binary files which you can hold in memory you can try following approach.

    fileNames.stream()
                .map(Paths::get)
                .filter(Files::exists)
                .map(path -> {
                    try {
                        return Files.readAllBytes(path);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .map(String::new)
                .forEach(System.out::println);
    

    Other than that I think you would have to use some wrapper class, where I could suggest Map.Entry or the Pair from javafx so you don't have to use any external libraries.

提交回复
热议问题