Java - File Input Output Paths Normalizing

Introduction

The normalize() method from Path interface returns a Path after removing dot, double dots.

This method does not access the file system.

A normalized path may not locate the same file as the path contained a symbolic link.

The following code shows some examples of normalizing paths on Windows.

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\\..\\\\myData\\Main.java");
    Path p1n = p1.normalize();/*from  www.  ja  v  a 2s  . co  m*/
    System.out.println(p1 + " normalized to " + p1n);

    Path p2 = Paths.get("C:\\myData\\Main.java");
    Path p2n = p2.normalize();
    System.out.println(p2 + " normalized to " + p2n);

    Path p3 = Paths.get("a\\..\\.\\test.txt");
    Path p3n = p3.normalize();
    System.out.println(p3 + " normalized to " + p3n);
  }
}

Result

Related Topic