javaslang / Vavr:如何尝试使用资源

时间:2018-08-08 09:01:15

标签: java-8 try-with-resources vavr

这是我的代码段:

 public static void main(String[] args) {

    Try.of(Main::getLines)
            .onFailure(cause -> log.error("An error has occurred while parsing the file", cause));
}

private static List<Fiche> getLines() {
    return Files.lines(Paths.get("insurance_sample.csv"))
            .skip(1)
            .map(Main::toPojo)
            .filter(fiche -> fiche.getPointLongitude().equals(-81.711777))
            .peek(fiche -> log.info("Fiche added with success {}", fiche))
            .collect(Collectors.toList());
}

我将获得Use try-with-resources或在“ finally”子句中关闭此“ Stream”。在这一行Files.lines(Paths.get("insurance_sample.csv"))

任何人都可以帮助我使用Vavr使用try-with-resources吗?

1 个答案:

答案 0 :(得分:1)

将对Files#lines(Path)的呼叫包装到Try#withResources中,如下所示:

List<String> lines = Try.withResources(() -> Files.lines(Paths.get("/hello.csv")))
        .of(stream -> stream.collect(Collectors.toList()))
        .getOrElseThrow(() -> new IllegalStateException("Something's wrong!"));