Remove redundancies by normalizing a path in Java

Description

The following code shows how to remove redundancies by normalizing a path.

Example


/*www.j  av a  2s.  c  o  m*/
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) {
    Path path = Paths.get("/home/docs/../music/A.mp3");
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("Normalized Path: " + path.normalize());
    System.out.println("Normalized URI: " + path.normalize().toUri());
    System.out.println();

    path = Paths.get("/home/./music/A.mp3");
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("Normalized Path: " + path.normalize());
    System.out.println("Normalized URI: " + path.normalize().toUri());

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip