Getting to know about java.nio.file.Path – 1


The last few released of Java namely Java 7, Java 8 and the upcoming Java 9 have quite a lot of features which makes the life of Java developers easier. (I know Java 9 will make it tougher, but only while you adopt the new paradigm. After that it’s going to be much better).

One of the features or API was the enhancements of the File API introduced in Java 7. One of the new classes of that feature set is java.nio.file.Path and its factory java.nio.file.Paths.

Maven Dependencies

We will be using JUnit and AssertJ to write our tests to demonstrate the API.

    <!-- use 2.8.0 for Java 7 projects -->

Creating an instance of java.nio.file.Path

As I mentioned before java.nio.file.Paths is the creator for java.nio.file.Path that is it provides two factory methods:

  • static Path get(String first, String … more)
  • static Path get(URI uri)

that can be used to get an instance of java.nio.file.Path. Let us look at the two ways to obtain the instance:

public void testPathCreation(){
    Path path = Paths.get("src", "main", "resources");

    Path uriPath = Paths.get(URI.create("file:///Users/Mohamed/git"));

Exploring the APIs

Using endsWith()

This method is used to check if a given Path object ends with another Path object or a path represented as a String object.

public void testEndsWith(){
    Path path = Paths.get("src", "main", "resources");

Using getFileName()

This method returns the name of the directory or the file present at the terminal or end of the path.

public void testGetFileName(){
    Path path = Paths.get("src", "main", "resources");
    path = Paths.get("src", "test", "java", "info", 

Using getFileSystem()

This method returns an instance of java.nio.file.FileSystem representing the underlying file system. We will look at this in detail in a future post.

public void testGetFileSystem(){
    Path path = Paths.get("src", "main", "resources");

Using getName() and getNameCount()

The getNameCount() returns number of name components present in the path where each name component is seperated by a file seperator. And the method getName() takes an index and returns the name component at the index.

For example  a given path: /var/log/myapp/spring.log has 4 name components and the component position is 0 based. So the name component at index 1 is log.

public void testGetName(){
    Path path = Paths.get("src", "main", "resources");

    assertThat(path.getName(path.getNameCount() - 1))

Using getParent()

This API returns the path from the root of a path until the terminal directory or file (i.e excluding it). For example: invoking getParent() on a Path instance representing /var/log/myapp/spring.log returns a Path instance representing /var/log/myapp

It returns null if the given path has no parent or if it is the root directory.

public void testGetParent(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getParent()).isEqualTo(Paths.get("src", "main"));

Using getRoot()

This API returns a Path instance of the root if it exists or null for a given instance of Path.

public void testGetRoot(){
    Path path = Paths.get("src", "main", "resources");

    path = Paths.get("/users", "Mohamed", "git", "blogsamples");

Using normalize()

This API is a bit tricky. It removes redundant elements in your path. Redundant elements are those whose removal will eventually result in a similar Path. For example: if we have a path src\..\src\main\java is equivalent to src\main\java. The normalize() API helps in achieving the latter from the former.

public void testNormalize(){
    Path path = Paths.get("src","..", "src", "main", "resources", ".");

Using subpath()

This method returns a sub path identified by the lower bound and upper bound which are passed as parameters to the method. The upper bound is excluded while computing the sub path.

public void testSubpath(){
    Path path = Paths.get("Mohamed", "git", 
            "blogsamples", "src", "main", "resources");
    assertThat(path.subpath(2, 3).toString()).isEqualTo("blogsamples");
    assertThat(path.subpath(0, path.getNameCount()).toString())

Using toAbsolutePath()

This method returns the absolute path for the given path. An absolute path originates from the root of the file system.

public void testToAbsolutePath(){
    Path path = Paths.get("src", "main", "resources");

Using toFile()

This is a very handy way to create an instance of We can leverage the use of creating a Path object with multiple folder levels and then use toFile() to get an instance of File.

public void testToFile(){
    Path path = Paths.get("src", "main", "resources");
    File file = path.toFile();

Using toRealPath()

This method can be used to resolve a symbolic link to its real location. To test this API we create a symbolic link:

On windows you would use:

mklink /D "C:\blogsample" "C:\Users\Mohamed\git\blogsamples"

On Linux, you would use

ln -s /var/log/sample.log sample

The method takes an option of type LinkOption. As of now, this enum has one element i.e NOFOLLOW_LINKS. If this option is passed then the symbolic link is not resolved to its real path.

public void testToRealPath() throws IOException {
    Path path = Paths.get( "/blogsample");

Using toUri()

This method returns a URI representation of a given path. Generally, on Windows, you would see something of the form: file:///C:/. But this is system dependent

public void testToUri(){
    Path path = Paths.get("src", "main", "resources");

Note: It’s important to note that the return type of most of the APIs is an instance of java.nio.file.Path. This helps us in chaining multiple methods and invoke them on a single java.nio.file.Path instance.

In the next article, we will look at the remaining few APIs in java.nio.file.Path.


3 thoughts on “Getting to know about java.nio.file.Path – 1

  1. Akai

    Hi Mohamed,
    What do you get when you instantiate a path with .toFile() ? A File object that contains all the files existing in the targeted folder ?


    1. Mohamed Sanaulla Post author

      From the Javadocs: Returns a File object representing this path.

      So it represents either a file or a directory (whichever the path is pointing to). You can confirm if its s directory by using File#isDirectory() or if its a normal file File#isFile(). And the File object is a representation of the file/directory on the filesystem.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s