Java Reference
In-Depth Information
Listing 10-2 demonstrates how to access components of a Path object. One of the paths used in this example is a
Windows-based path. If you are not running the program on Windows, please change the path in the main() method
to represent a valid path on your platform. You may get a different output when you run the program.
Listing 10-2. Demonstrating How to Access Components of a Path
// PathComponentsTest.java
package com.jdojo.nio2;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathComponentsTest {
public static void main(String[] args) {
Path p1 = Paths.get("C:\\poems\\luci1.txt");
printDetails(p1);
System.out.println("----------------------");
Path p2 = Paths.get("luci1.txt");
printDetails(p2);
}
public static void printDetails(Path p) {
System.out.println("Details for path: " + p);
int count = p.getNameCount();
System.out.println("Name count: " + count);
for(int i = 0; i < count; i++) {
Path name = p.getName(i);
System.out.println("Name at index " + i + " is " + name);
}
Path parent = p.getParent();
Path root = p.getRoot();
Path fileName = p.getFileName();
System.out.println("Parent: " + parent + ", Root: " + root +
", File Name: " + fileName);
System.out.println("Absolute Path: " + p.isAbsolute());
}
}
Details for path: C:\poems\luci1.txt
Name count: 2
Name at index 0 is poems
Name at index 1 is luci1.txt
Parent: C:\poems, Root: C:\, File Name: luci1.txt
Absolute Path: true
----------------------
 
Search WWH ::




Custom Search