Java program to get the relative path from two absolute paths

https://‮tfigi.www‬idea.com

To get the relative path between two absolute paths, we can use the java.nio.file.Path class in Java. Here is an example program that demonstrates this:

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

public class RelativePathExample {
    public static void main(String[] args) {
        // define the absolute paths
        Path path1 = Paths.get("C:\\Users\\User\\Documents\\file1.txt");
        Path path2 = Paths.get("C:\\Users\\User\\Downloads\\file2.txt");
        
        // get the relative path
        Path relativePath = path1.relativize(path2);
        
        // print the relative path
        System.out.println("Relative path: " + relativePath);
    }
}

In this program, we first define two absolute paths using the Paths.get() method. Then, we use the relativize() method of the Path class to get the relative path between the two paths. Finally, we print the relative path to the console.

Note that the relativize() method can throw an IllegalArgumentException if the two paths have different roots or are not both absolute. In such cases, we need to handle the exception appropriately.