Saïd R.
Saïd R.

Reputation: 71

javaslang/Vavr : How to do a try with resource

Here is my code snippet :

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

I'm getting Use try-with-resources or close this "Stream" in "finally" clause. on this line Files.lines(Paths.get("insurance_sample.csv"))

Anyone can help me to use a try-with-resources using Vavr?

Upvotes: 7

Views: 3711

Answers (1)

Selim
Selim

Reputation: 1132

Wrap the call to Files#lines(Path) into Try#withResources like so:

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

Upvotes: 8

Related Questions