Java Programming Tutorials

Java programming tutorials with many code examples!

Java Path parent and other parts

Java Path get parent and other path parts

In this tutorial we’re going to show how to access different parts of java.nio.file.Path from Java NIO.

Get parent directory

Path.getRoot() and Path.getParent() gives access to parts of path:

Path path = Paths.get("/proc/nested/version");
System.out.println("root: " + path.getRoot());
System.out.println("parent: " + path.getParent());

The above code produces the following:

root: /
parent: /proc/nested

Mind that Path.getParent() returns all descendants of the current path – without filename.

Getting parts of path

Using Path.getName() we can access any part of a path:

Path path = Paths.get("/proc/nested/version");
System.out.println("Number of parts: " + path.getNameCount());
System.out.println("top parent: " + path.getName(0));
System.out.println("direct parent: " + path.getName(1));
System.out.println("filename: " + path.getName(2));

The above code produces:

top parent: proc
direct parent: nested
filename: version

Iterate over parts of path

To do that we can use Path.iterator() to iterate over the parts and collect them using Iterator.forEachRemaining(), which is a new default method in Iterator interface. So it’s strictly Java 8 solution.

Path path = Paths.get("/proc/nested/version");

List<Path> parts = new LinkedList<>();

if (parts.size() > 1) {
    System.out.println("Parent using iterator: "
        + parts.get(parts.size()-2));

Note that object::method notation is Java 8 way of passing object’s method to another method for execution. It simply means that the add method of parts object will be called with each element taken from the iterator.

The above code prints:

Parent using iterator: nested


Share with the World!