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?
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.
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 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.
Vavr is a functional library for Java 8+ that provides immutable data types and functional control structures.
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!"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With