Java - Path Absolute Path, Real Path, URI

Introduction

You can get different type of representations for a path.

Suppose you create a Path object representing a relative path as follows:

Path p1 = Paths.get("test.txt");

You can get the absolute path that is represented by p1 using its toAbsolutePath() method as follows:

// Get the absolute path represented by p1
Path p1AbsPath = p1.toAbsolutePath();

p1AbsPath is the absolute path for p1.

If the path is an absolute path, the toAbsolutePath() method returns the same path.

You can use the toRealPath() method to get the real path of an existing file.

If the path represents a symbolic link, it returns the real path of the target file.

You can pass a link option to indicate whether to follow the symbolic link to its target.

If the file represented by the path does not exist, the toRealPath() throws an IOException.

The following code demonstrates how to get the real path from a Path object:

Demo

import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    try {//from  w  w  w .  ja v a 2  s .  co m
      Path p2 = Paths.get("test2.txt");

      // Follow link for p2, if it is a symbolic link
      Path p2RealPath = p2.toRealPath();

      System.out.println("p2RealPath:" + p2RealPath);
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      Path p3 = Paths.get("test3.txt");

      // Do not follow link for p3, if it is a symbolic link
      Path p3RealPath = p3.toRealPath(LinkOption.NOFOLLOW_LINKS);

      System.out.println("p3RealPath:" + p3RealPath);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

toUri()

toUri() method of Path object returns its URI representation.

A URI representation of a path is platform-dependent.

A URI form of a path can be used in a browser to open the file indicated by the path.

The following code shows how to get the URI form of a path.

Demo

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

public class Main {
  public static void main(String[] args) {
    Path p2 = Paths.get("test2.txt");
    java.net.URI p2UriPath = p2.toUri();
    System.out.println("Absolute Path: " + p2.toAbsolutePath());
    System.out.println("URI Path: " + p2UriPath);
  }//from  w  w  w .  j a v  a2  s  .c  o  m
}

Result

Related Topic