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

Introduction

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.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <!-- use 2.8.0 for Java 7 projects -->
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>

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:

@Test
public void testPathCreation(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.isAbsolute()).isFalse();
    assertThat(path.toString()).isEqualTo("src\\main\\resources");

    Path uriPath = Paths.get(URI.create("file:///Users/Mohamed/git"));
    assertThat(uriPath.isAbsolute()).isFalse();
    assertThat(uriPath.toAbsolutePath().toString())
            .isEqualTo("C:\\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.

@Test
public void testEndsWith(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.endsWith(Paths.get("main","resources"))).isTrue();
    assertThat(path.endsWith("resources")).isTrue();
}

Using getFileName()

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

@Test
public void testGetFileName(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getFileName().toString()).isEqualTo("resources");
    path = Paths.get("src", "test", "java", "info", 
        "sanaulla","PathDemoTest.java");
    assertThat(path.getFileName().toString())
        .isEqualTo("PathDemoTest.java");
}

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.

@Test
public void testGetFileSystem(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getFileSystem()).isNotNull();
    assertThat(path.getFileSystem().getSeparator()).isEqualTo("\\");
    path.getFileSystem().getRootDirectories().forEach(System.out::println);
}

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.

@Test
public void testGetName(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getName(0)).isEqualTo(Paths.get("src"));

    assertThat(path.getName(path.getNameCount() - 1))
            .isEqualTo(Paths.get("resources"));
}

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.

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

Using getRoot()

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

@Test
public void testGetRoot(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getRoot()).isNull();

    path = Paths.get("/users", "Mohamed", "git", "blogsamples");
    assertThat(path.getRoot()).isEqualTo(Paths.get("/"));
}

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.

@Test
public void testNormalize(){
    Path path = Paths.get("src","..", "src", "main", "resources", ".");
    assertThat(path.toString())
            .isEqualTo("src\\..\\src\\main\\resources\\.");
    assertThat(path.normalize().toString())
            .isEqualTo("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.

@Test
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())
            .isEqualTo("Mohamed\\git\\blogsamples\\src\\main\\resources");
}

Using toAbsolutePath()

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

@Test
public void testToAbsolutePath(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.toAbsolutePath().toString())
       .isEqualTo("C:\\Users\\Mohamed\\git\\blogsamples\\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 and then use toFile() to get an instance of File.

@Test
public void testToFile(){
    Path path = Paths.get("src", "main", "resources");
    File file = path.toFile();
    assertThat(file).isNotNull();
    assertThat(file.isDirectory()).isTrue();
    assertThat(file.exists()).isTrue();
}

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.

@Test
public void testToRealPath() throws IOException {
    Path path = Paths.get( "/blogsample");
    assertThat(path.toRealPath().toString())
            .isEqualTo("C:\\Users\\Mohamed\\git\\blogsamples");
    assertThat(path.toRealPath(LinkOption.NOFOLLOW_LINKS).toString())
            .isEqualTo("C:\\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

@Test
public void testToUri(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.toUri()).isEqualTo(
      URI.create("file:///C:/Users/Mohamed/git/blogsamples/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.

Advertisements

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 ?

    Like

    Reply
    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.

      Like

      Reply

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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