Over a million developers have joined DZone.

Getting to Know java.nio.file.Path (Part 1)

DZone's Guide to

Getting to Know java.nio.file.Path (Part 1)

Java 9 will be introducing a number of enhancements to the File API. Let's run through most of them and see how they'll simplify your work.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

The last few releases of Java, namely Java 7, Java 8, and the upcoming Java 9, have quite a lot of features to make the lives 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 new features is the enhancement 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. It provides two factory methods:

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

Those 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 four 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 it reaches 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, the 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 java.io.File. We can leverage the use of creating a Path object with multiple folder levels, 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: 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 in 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 API is an instance of java.nio.file.Path. This helps us in chaining multiple methods and invoking 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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

java ,java 9 ,file api ,file path ,tutorial

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}