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 sub-path you can use the subpath()
method and specify the starting and ending indexes. The code snippet below demonstrate to you how to get these information.
package org.kodejava.example.io;
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$s%n", notepad.getFileName());
System.out.printf("Name count : %1$s%n", notepad.getNameCount());
System.out.printf("Parent path : %1$s%n", notepad.getParent());
System.out.printf("Root path : %1$s%n", notepad.getRoot());
System.out.printf("Sub path from root: %1$s%n", notepad.subpath(0, 2));
}
}
This code will print something like:
File name : notepad.exe
Name count : 3
Parent path : C:\Windows\System32
Root path : C:\
Sub path from root: Windows\System32
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020