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.example.nio;

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
        // removed when we are working on the current directory.
        //
        Path path = Paths.get("./README");
        System.out.println("Path = " + path);

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

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply