Java - Path Components Accessing

Introduction

A path in a file system can have one or more components or sub pathes.

The methods of the Path interface can access those components.

getNameCount() method returns the number of components in a Path object excluding the root.

For example, the path C:\myData\Main.java consists of three components: a root of C:, and two components named myData and Main.java.

For this value the getNameCount() method will return 2.

getName(int index) method returns the component name at the specified index.

The component closest to the root has an index of 0.

The component farthest from the root has an index of count - 1.

In the path C:\myData\Main.java, the myData component has an index of 0 and the Main.java component has an index of 1.

getParent() method returns the parent of a path. If a path does not have a parent, it returns null.

For example, the parent of the path C:\myData\test.txt is C:\myData.

The relative path test.txt has no parent.

getRoot() method returns the root of the path. If a path does not have a root, it returns null.

For example, the path C:\myData\Main.java on Windows has C:\ as its root.

getFileName() method returns the file name denoted by the path. If a path has no file name, it returns null.

The file name is the farthest component from the root. For example, in the path C:\myData\Main.java, Main.java is the file name.

To check if a path represents an absolute path, use the isAbsolute() method.

A path does not have to exist in the file system to get information about its components.

Path interface uses the information in the path string to give you all these pieces of information.

The following code demonstrates how to access components of a Path object.

Demo

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

public class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("C:\\myData\\Main.java");
    printDetails(p1);/*from ww w.j  av  a2 s.com*/

    Path p2 = Paths.get("Main.java");
    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());
  }
}

Result

Related Topic