Java NIO Path

Java7 Introduced NIO2 as an enhancement to the current File API. Java NIO Path and especially Path class was one of the main entry points for NIO2 API.

Path class is a representation of the underlying platform file system.Path class will create a path based on the platform you are working on. (e.g. For Linux system Path class represents  path as /user/home while for window it will represent path as C:/home/my-folder).

Path class work very closely with the utility class Files introduced as part of the Java 7 NIO package and provide different utility methods to work on the file system.

Some of the common methods and information being returned by Path class are

  1. Creating Path to represent underlying platform path system.
  2. Access element of the Path.
  3. Comparing 2 paths
  4. Joining 2 paths

 

Keep in mind that all above operation using Path class operates on the path itself and not on the underlying file system. We need to use utility class Files in combination with Path class to access and work on the file system.

 

Path Operations

We will cover various operation performed on the Path class with information as to how to build a path to access the underlying file system.

 

1.  Creating Path 

Path is nothing but a representation or the location of the file or directory in your file system or on the system where you are planning to run this programme.Java NIO Path class provide a convenient way to create a path using Paths.get() method.

 

package com.umeshawasthi.tutorials.corejava.io.path;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by umesh on 5/31/17.
 */
public class CreatePath {

    public static void main(String[] args) {

        Path path = Paths.get("/Users/umesh/personal/tutorials");
        
        Path path1 = Paths.get(URI.create("file:/Users/umesh/personal/tutorials"));
        
        Path path2= Paths.get(System.getProperty("user.home"),"personal", "tutorials");

        System.out.println(path2.toAbsolutePath());
        System.out.println(path1.toAbsolutePath());
        System.out.println(path.toAbsolutePath());
    }
}

 

Output

/Users/umesh/personal/tutorials 
/Users/umesh/personal/tutorials 
/Users/umesh/personal/tutorials

Paths is another utility class provided with Java NIO with a set of static methods for creating Path object for a given String or URI.

Paths.get() method will internally use FileSystems.getDefault().getPath() to get Path represnetation based on the platform.

FileSystems will be using code class=”language-java”>FileSystemProvider to get a concrete implementation file system provider based on the given platform (Windows will have different FileSystemProvider than Linux)

 

public class CreatePath {

    public static void main(String[] args) {

        Path path = Paths.get("/Users/umesh/personal/tutorials/source");
        pathMethod(path);
    }

    public static void pathMethod(Path path) {

        System.out.println("toString method :: " + path.toString());
        System.out.println("getFileName :: " + path.getFileName());
        System.out.println("getFileSystem :: " + path.getFileSystem());
        System.out.println("Get Root Name :: " + path.getRoot());
        System.out.println("Get Parent ::" + path.getParent());
        System.out.println("get count :: " + path.getNameCount());
    }
}

 

Output

toString method :: /Users/umesh/personal/tutorials/source
getFileName :: source
getFileSystem :: sun.nio.fs.MacOSXFileSystem@5e2de80c
Get Root Name :: /
Get Parent ::/Users/umesh/personal/tutorials
get count :: 5

Pay close attention to the output of the getFileSystem, I am running this programme on MacOSX, so the MacOSXFileSystem is being returned as the underlying FileSystemProvider. If you run this programme on Windows, you will see a different output for this.

 

2.  Converting to Path 

Path Object provides different options to convert Path representation to String. We can use following options with Path

  1. Path.toURI ( For using it in the browser).
  2. Path.toAbsoultePath (For absolute path)
  3. Path.toRealPath (Getting real path including symbolic links)

 

public class DisplayPath {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("/Users/umesh/personal/tutorials/source");

        System.out.format("toURI: %s%n", path.toUri());
        System.out.format("toAbsolutePath: %s%n", path.toAbsolutePath());
        System.out.format("toRealPath: %s%n", path.toRealPath());
    }
}

 

Output


toURI: file:///Users/umesh/personal/tutorials/source/

toAbsolutePath: /Users/umesh/personal/tutorials/source

toRealPath: /Users/umesh/personal/tutorials/source

 

3.  Joining Path 

What is mean by joining path? Joining path means, you will combine root path with the partial path with the help of resolve method.

Read Copy a File or Directory in Java to get an understanding to use relativize and resolve methods.

 

4.  Comparing Two Paths

Path class provide support to compare two paths to check if both paths point to the same location. Keep in mind that Path.equals() method will be dependent upon the underlying file system.

public class PathEquality {

    public static void main(String[] args) throws IOException {

        Path path = Paths.get("/Users/umesh/personal/tutorials/source");
        Path path1 = Paths.get("/Users/umesh/personal/tutorials/source");

        System.out.println(path.equals(path1));
    }
}

 

If you want to check path for a specific name, you can use startsWith() and endsWith() methods.

There are a couple of interesting points about the Path class.

  1. Path class implement the Iterable interface which will help you to iterate over name element in the Path class.
  2. You can also compare two path object as Path class also implements the Comparable interface.

 

public class PathIterate {

    public static void main(String[] args) {

        Path paths= Paths.get("/Users/umesh/personal/tutorials/source/bootstrap",
                "/Users/umesh/personal/tutorials/source/build",
                "/Users/umesh/personal/tutorials/source/dist");

        for (Path path :paths){
            System.out.println(path.toAbsolutePath());
        }
    }
}

In this post, we get a basic understanding of the Java NIO Path class along with some of the methods and features being supported by it.

Good understanding of the Path class along with Files class is a good building block for understanding NIO and NIO2 introduced in Java7

 

All the code of this article is available Over on Github. This is a Maven-based project.

Comments are closed.