Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Saïd R. Avatar asked Aug 08 '18 09:08

Saïd R.


People also ask

What is try run in Java?

Java try block is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement in the try block, the rest of the block code will not execute.

How do you release a resource in Java?

Because a finally block always executes, it typically contains resource-release code. Suppose a resource is allocated in a try block. If no exception occurs, the catch blocks are skipped and control proceeds to the finally block, which frees the resource.

What is either in Java?

What Is Either? In a functional programming world, functional values or objects can't be modified (i.e. in normal form); in Java terminology, it's known as immutable variables. Either represents a value of two possible data types. An Either is either a Left or a Right.

What is VAVR io?

Vavr is a functional library for Java 8+ that provides immutable data types and functional control structures.


1 Answers

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!"));
like image 143
Selim Avatar answered Sep 19 '22 22:09

Selim