Java Path getParent()

In this guide, you will learn about the Path getParent() method in Java programming and how to use it with an example.

1. Path getParent() Method Overview

Definition:

The getParent() method of the Path interface in the Java NIO (New I/O) package returns the parent path of the current path or null if this path does not have a parent.

Syntax:

Path getParent()

Parameters:

- None

Key Points:

- If the path has one or more elements, this method returns a new Path object containing the elements from the beginning of the path up to, but not including, the last element.

- If the path has only one element, or if it's an empty path, the method returns null.

- It is useful when navigating file directories and needing to move one level up in the directory structure.

2. Path getParent() Method Example


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

public class PathGetParentExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("C:", "Users", "JohnDoe", "Documents", "myfile.txt");
        Path parentPath = filePath.getParent();
        System.out.println("Original path: " + filePath);
        System.out.println("Parent path: " + parentPath);

        Path singleElementPath = Paths.get("myfile.txt");
        Path noParentPath = singleElementPath.getParent();
        System.out.println("Single element path: " + singleElementPath);
        System.out.println("Parent of single element path: " + noParentPath);
    }
}

Output:

Original path: C:\Users\JohnDoe\Documents\myfile.txt
Parent path: C:\Users\JohnDoe\Documents
Single element path: myfile.txt
Parent of single element path: null

Explanation:

In the example, we first obtain the parent of a path that points to a file myfile.txt located deep within a directory structure. The returned parent path excludes the myfile.txt component. 

Then, we try to get the parent of a single-element path (myfile.txt). Since there's no parent in this case, the method returns null.

Comments