How to get some information about Path object?

The java.nio.Path provides some methods to obtain information about the Path. For example you can get information about the file name, the parent and the root path. For these you can call the getFileName(), getParent() and getRoot() method respectively.

You can also get the number of elements that make up this Path using the getNameCount() method. And to get the subpath you can use the subpath() method and specify the starting and ending indexes. The code snippet below demonstrate to you how to get these informations.

package org.kodejava.example.nio;

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

public class PathInfoExample {
    public static void main(String[] args) {
        // Create a Path for Windows notepad program.
        Path notepad = 

        // Get some information about the Path object.
        System.out.printf("File name         : %1$sn", 
        System.out.printf("Name count        : %1$sn", 
        System.out.printf("Parent path       : %1$sn", 
        System.out.printf("Root path         : %1$sn", 
        System.out.printf("Sub path from root: %1$sn", 
                notepad.subpath(0, 2));

This code will print something like:

File name         : notepad.exe
Name count        : 3
Parent path       : C:WindowsSystem32
Root path         : C:
Sub path from root: WindowsSystem32


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply