Welcome to the World of Online Learning:
Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Write a Java Program to Get the relative path from two absolute paths
PROGRAM: Java Program to Get the relative path from two absolute paths
/*Java Program to Get the relative path from two absolute paths*/
1: Get a relative path from two absolute paths using URI class
import java.io.File;
import java.net.URI;
class Main {
public static void main(String[] args) {
try {
// Two absolute paths
File absolutePath1 = new File(“C:\\Users\\Desktop\\Programiz\\Java\\Time.java”);
System.out.println(“Absolute Path1: ” + absolutePath1);
File absolutePath2 = new File(“C:\\Users\\Desktop”);
System.out.println(“Absolute Path2: ” + absolutePath2);
// convert the absolute path to URI
URI path1 = absolutePath1.toURI();
URI path2 = absolutePath2.toURI();
// create a relative path from the two paths
URI relativePath = path2.relativize(path1);
// convert the URI to string
String path = relativePath.getPath();
System.out.println(“Relative Path: ” + path);
} catch (Exception e) {
e.getStackTrace();
}
}
}
2: Get a relative path from two absolute path using String methods
import java.io.File;
class Main {
public static void main(String[] args) {
// Create file objects
File file1 = new File(“C:\\Users\\Desktop\\Programiz\\Java\\Time.java”);
File file2 = new File(“C:\\Users\\Desktop”);
// convert file objects to string
String absolutePath1 = file1.toString();
System.out.println(“Absolute Path1: ” + absolutePath1);
String absolutePath2 = file2.toString();
System.out.println(“Absolute Path2: ” + absolutePath2);
// get the relative path
String relativePath = absolutePath1.substring(absolutePath2.length());
System.out.println(“Absolute Path: ” + relativePath);
}
}
3: Get a relative path from two absolute paths using java.nio.file package
import java.nio.file.Path;
import java.nio.file.Paths;
class Main {
public static void main(String[] args) {
// Create file objects
Path absolutePath1 = Paths.get(“C:\\Users\\Desktop\\Programiz\\Java\\Time.java”);
Path absolutePath2 = Paths.get(“C:\\Users\\Desktop”);
// convert the absolute path to relative path
Path relativePath = absolutePath2.relativize(absolutePath1);
System.out.println(“Relative Path: ” + relativePath);
}
}