Showing posts with label java.nio.file. Show all posts
Showing posts with label java.nio.file. Show all posts

Sunday, April 12, 2020

Java 8 Optional orElseThrow() Example | Throw Exception in Optional in Java 8

1. introduction


In this tutorial, We'll learn how to throw an exception if the option is empty. Optional API orElseThrow() method returns value from Optional if present. Otherwise, it will throw the exception created by the Supplier.

2. Syntax


public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                                    throws X extends Throwable


Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

A method reference to the exception constructor with an empty argument list can be used as the supplier. For example, IllegalStateException::new, ArithmeticException::new

Wednesday, August 14, 2019

Java 8 Files walk() Examples

1. Overview


In this tutorial, We'll be learning the Files API walk() method in java 8. walk() method is part of the Files class and java.nio.file package.

This method is used to walk through any given directory and retrieves Stream<Path> as the return value. This method traverses through all its subdirectories as well.

API Description:

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

Note: This method must be used within a try-with-resources statement.

In this article, We'll see its syntax and example programs on how to list all the files in the directory, list directories and specific file patterns such as .csv or file name contains 'Match' word.