The NIO.2 Path Class

The Path class is considered to be the entry point for exploring the NIO.2 API. Basically every I/O operation in NIO.2 will exploit the facilities offered by this class.

Path is basically an upgraded version of the java.io.File class.

1. Getting the Path of the Home Directory When you want to obtain the path that points to a specific file in the Home directory, you can proceed as shown. The returned home directory is dependent on each operating system:


2. Obtaining information about the Path: Path Root and Path Parent 


3. Splitting a path in its name elements This is a nice feature that allows the programmer to split the path in it’s forming elements. For example if a file has the following path: ‘C:\Users\andreinc\Downloads\file1.txt’ the following function will retrieve the forming elements of the path, a List containing the following elements: [‘C:\’, ‘Users’, ‘andreinc’, ‘Downloads’, ‘file1.txt’] .

And the output is:


4. Getting the subpath We can extract a relative path using a subpath method. This method accept two parameters, the start (index) and end (index) in the subsequence of elements.

And the output is:


5. Combining two paths
This allows you to define a fixed root path and append to it partial paths.

Output:


6. Comparing two paths
Two paths can be compared as objects, using the “equals()” function. This method is related to the “equals()” method of class Object, thus the compared paths are not required to exist, and this method does not check if the paths are the same file.

But sometimes we want to check if two Path objects represent the same file / folder . In this case we will need to use java.nio.File.Files.isSameFile() method.

Eg.:

Output:

The Path class implements the Comparable interface, thus we can compare two paths by using the compareTo() method . The comparation will be lexicographical, so this will be useful for “sorting”.


7. Iterating over the elements of a Path

The Path class implements the Iterable interface, so we can use a foreach to iterate over the elements of a Path.

Eg.:

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *

Are we human, or are we dancer *