【问题标题】:javaslang/Vavr : How to do a try with resourcejavaslang/Vavr:如何尝试使用资源
【发布时间】:2018-08-08 09:01:15
【问题描述】:

这是我的代码 sn-p :

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

我正在使用 try-with-resources 或在“finally”子句中关闭此“Stream”。在这条线上Files.lines(Paths.get("insurance_sample.csv"))

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

【问题讨论】:

  • Try.withResources?
  • Try.withResources 期待 CheckefFunction 而 getLines 方法返回一个 List

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


【解决方案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!"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2020-07-04
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多