Get the relative path between two paths in Java

Description

The following code shows how to get the relative path between two paths.

Example


/*from  ww w .  j  a va  2  s .c  o m*/
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) {
    Path firstPath = Paths.get("music/A.mp3");
    Path secondPath = Paths.get("docs");

    System.out.println("From firstPath to secondPath: "
        + firstPath.relativize(secondPath));
    System.out.println("From secondPath to firstPath: "
        + secondPath.relativize(firstPath));
    System.out.println();

  }
}

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