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 = 
                Paths.get("C:\Windows\System32\notepad.exe");

        //
        // Get some information about the Path object.
        //
        System.out.printf("File name         : %1$sn", 
                notepad.getFileName());
        System.out.printf("Name count        : %1$sn", 
                notepad.getNameCount());
        System.out.printf("Parent path       : %1$sn", 
                notepad.getParent());
        System.out.printf("Root path         : %1$sn", 
                notepad.getRoot());
        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

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.