Java - File Input Output Paths Relativizing

Introduction

Relativizing is to get a relative path for a given path against another path.

relativize(Path p) returns relative path.

A relative path cannot be obtained if one of the paths has a root element.

The following code has some examples of getting relative paths.

Demo

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

public class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("myData");
    Path p2 = Paths.get("myData", "recent", "Data");
    System.out.println(p1.relativize(p2));
    System.out.println(p2.relativize(p1));

    Path p3 = Paths.get("Doug");
    Path p4 = Paths.get("Bobby");
    System.out.println(p3.relativize(p4));
    System.out.println(p4.relativize(p3));
  }/*from   w  w w. j  a  v a 2  s. c om*/
}

Result

Related Topic