How do I remove redundant elements from a Path?

To eliminate redundant elements from a Path we can use the Path.normalize() method. For example in the following code snippet. When try accessing the README file in the current directory the . symbol in the Path elements considered to be redundant, we don’t need it. That’s why we normalize the Path.

package org.kodejava.io;

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

public class PathNormalize {
    public static void main(String[] args) {
        // The following Path contains a redundant element. The "." which 
        // basically point to the current directory can simply be removed
        // when we are working on the current directory.
        Path path = Paths.get("./README.md");
        System.out.println("Path = " + path);

        // Removes redundant name elements from the path.
        path = path.normalize();
        System.out.println("Path = " + path);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.