Skip to main content

Java NIO.2 - The Path Class - An overview

The Java NIO.2 is a new API for file manipulation. Added to the Java Platform 7. This API comes with many benefits, and new classes. Those classes bring new functionalities, and solve problems of the traditional I/O API, as well as allow a more robust and simpler code.

In this article, we are going to talk about one of the base classes: The Path class, present in the java.nio.File package. This class is basically one of the entry class of the Java NIO API.

The models the Path of File or a directory in a File System in a particular Operational System - Microsoft Windows, for example. As we are a bout to see, this class offers many facilities that make it very important and present in other I/O Operations, as well as, it plays an important role with other classes in the NIO API.

Let us get started in the journey of the Path class and its use.

1. Intancing a Path

The Path, is actually an Interface, that is instanced with a static factory method from the utility class Paths(java.nio.file.Paths). In our example we are going to use the path c:\LearningNIO\Test as our path. You don't have to create the path in order to test the methods we are going to learn.

Open your favorite IDE, and in a Class place the methods within a public static main method. Let's first create a new Path. Since I am using windows I will create the path String with a back slash, and therefore within the String I must scape one back slash with another, that is, i windows, I have to use two back slashes.

public static void main(String...strings){
    Path path = Paths.get("c:\\LearningNIO\\Test");

There's also another static factory method to create a new instance of a Path, the receives a URI object rather than a String.

Path path = Paths.get(uri);

Let's now go over the methods that make the Path powerful and easy to use.

2. Methods


Returns the name of the file or directory represented by this path as a Path object. The file name is the farthest element from the root in the directory hierarchy. In our case, using the path created above the path returned by this method is Test


Path.getName(int  index)

Returns the path element in the position, that is, the index argument. The first index is always 0, and it does not consider the root node, which means in are example, that the returning path is: LearningNIO


In the case of invoking the method with an invalid index, in our example it might be -1 or 2, the unchecked exception IllegalArgumentException is thrown.

- Path.getNameCount()

As you might have guessed, this method returns the number of elements in this Path, which in our path is 2. The root(C:) is not considered.


Returns the parent path, or null if this path does not have a parent. The path returned in our case is c:\LearningNIO


- Path.getRoot()

This method returns the root of the path if it has one, otherwise it returns null. In our example, the root component of the path 'c:\LearningNIO\Test' is 'c:'

- Path.subPath(int beginIndex, int endIndex) 

This method is useful and you want to get a sub path of a path object, as you might expect the return is a path object. A subpath is relative path that is a subsequence of the elements in the path you are invoking the subpath method. The element that is closest to the root element has the index 0, in our case, the element in the 0 index is LearningNIO. The farthest element from the root has the index count -1, which in our example is Test.

So, if we invoke the method with the arguments 0 and 1 the output is: LearningNIO


- Path.isAbsolute()

Returns true if the path is absolute or false otherwise. An absolute path is a path that does not need to be combined with other paths to locate a file, because it is complete. Our output is true.


- Path.startsWith(String other)

Returns true if the path starts with the path represented by the String used in the parameter, otherwise it returns false. Let's for example use the String C:\\ as argument and see the output:


By running this code snippet the output is true, in other words, yes, the path: 'c:\learningNIO\Test' starts with 'c:'. If we run the same code with the argument 'c:\LearningNIO', the return is also true. Now, if it is ran with the argument c:\\Test, return is false, because our path does not start with c:\Test.

Note that this method has an overloaded version that accepts a Path as Argument, and acts the same way.

System.out.println(path.startsWith( Paths.get("C:\\") ));

- Path.endsWith(String other)

Returns true if the path ends with the path represented by the String passed in the argument other. It acts the opposite way of startsWith method, and it also has an overloaded version that accepts a path object as parameter:
The output is false.

- Path.toAbsolutePath()

Returns a Path object representing the absolute path of this path. Let's use another path object to explain it:


The output of the code above is C:\Test\Test2

- Path.toRealPath()

Returns the real path of an existing file.

The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.
If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.

The options array may be used to indicate how symbolic links are handled. By default, symbolic links are resolved to their final target. If the option NOFOLLOW_LINKS is present then this method does not resolve symbolic links. Some implementations allow special names such as ".." to refer to the parent directory. When deriving the real path, and a ".." (or equivalent) is preceded by a non-".." name then an implementation will typically cause both names to be removed. When not resolving symbolic links and the preceding name is a symbolic link then the names are only removed if it guaranteed that the resulting path will locate the same file as this path.

try {
} catch (IOException e) {

As you can see we have to surround the method invocation with a try-catch block because this method checks if the path really exists in the File System. So far, we have been invoking many mthods and crating paths that don't have to exist, but in this case, when invoked this method throws an checked Exception. You might want to use this method for validation against paths. So in our case, if you don't want the exception printed, create the path.


Popular posts from this blog

Always Use StringBuilder while concatenating Strings within loops

A common tendency of Java programmers is to always concatenate Strings using + operator. Which is actually very good, and simplifies the code by improves readability, since we would have to use StringBuilder.append(String), if the single + operator was not allowed.

In fact if we look in byte code generate from such concatenation style, we will see a StringBuilder being used to perform the action.

Check the JSL: JLS

Now, the point is, although this facility, you should not use the + operator in loop concatenation.


A new StringBuilder Object will be constructed at every single loop iteration (with initial value of str) and at the end of every iteration there will be concatenation with initial String (actually StringBuilder with initial value of str).
So you need to create StringBuilder by yourself only when you work with String concatenation in loop.

Let us procuce the evidence

First, run this code, and see how long it takes to be executed:

Now, bellow is the code you should stick with, …

Maven Tips... and Tricks

Maven, one of the central actors in the Java World, resposible for managing the building life-cycles of many projects, is full of little features, that sometimes we forget to explore.

Let us go straight away and take a look at some very useful Maven features that will make your builds shine.

From where it stopped
Sometimes it is needed to build a bunch of projects all together, artifact-a, artifact-b and so on. What do we usually do when one of them fail? Build it all again!

But not anymore:

By using this option you can run the build from the project that failed.

Two out of ten

Ok, suppose you have 10 projects, and you only want to build 2 of them, how would you do?

The option -pl will do the job

Multi-threaded Build

If in the machine you run the build you have many Cores, tou can take advantage of them by using the following option(it means 2 Threads per Core):

It is also possible to define 3 Threads per Core(T3C)

Skip your Tests when you want to

With a lot of tests to perform your complete…

When to use NOSQL - An opinion based post of 2014...

In the last weeks, I've been hearing a lot about Cassandra, and other NoSQL Solutions that were candidates to one of the projects I am working on. Which is currently set to function properly with a RDBMS solution - Oracle 11g.

I decided then to take a deeper look into those kind of solution, NoSQL solutions, and compare them with RDBMS solutions. This article is intended to help you understand NoSQL, and pick the solution that best fits your requirements and scenario. This article does not cover all the features of a Specific NoSQL solution, rather it shows the general scenario.

In order to fully understand NoSQL, let us first see some key concepts of distributed computer systems and storage systems.

What is NoSQL?

A NoSQL or Not Only SQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases. Motivations for this approach include simplicity of design, horizontal scaling and finer contro…