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 this information.
package org.kodejava.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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024