Java Program to Get Relative path from two Absolute Paths

Java Program to Get Relative path from two Absolute Paths

What is Absolute Path ?

An absolute path in Java is a file or directory path that details a file or directory’s whole location within a file system, starting from the root directory.
Depending on the operating system, Java has a different syntax for specifying an absolute path. In a Unix-based system, the absolute path begins with a forward slash (e.g., “/home/john/documents/file.txt”), whereas in a Windows operating system, the absolute path might start with a drive letter followed by a colon (e.g., “C:UsersJohnDocumentsfile.txt”).

What is Relative Path  ?

A file or directory path established relative to the location of the file or directory being referenced or the current working directory is known as a relative path. As contrast to specifying an absolute path that starts from the root directory, a relative path starts from the present position and specifies the location of a file or directory relative to that location.

For Example : if the current working directory is /home/user, the file placed at /home/user/Documents/report.txt would be referenced by the relative path Documents/report.txt. The same relative path of report.txt would also point to the same file if the current working directory were /home/user/Documents.

Example 1 : Using File class

Run
import java.io.File;

public class Main {
    public static void main(String[] args) {
        // Define the absolute paths
        File file1 = new File("/home/user/Documents/report.txt");
        File file2 = new File("/home/user/Pictures/family.jpg");

        // Get the canonical path of the base directory
        File baseDir = new File(file1.getParent());
        try {
            baseDir = baseDir.getCanonicalFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get the relative path between the two paths
        String relativePath = baseDir.toURI().relativize(file2.toURI()).getPath();

        // Print the relative path
        System.out.println(relativePath);
    }
}

Output :

/home/user/Pictures/family.jpg

Explanation :

In this case, we get the parent directory of file1 to serve as the base directory and define the absolute paths using the File class. Then, in order to obtain the canonical path of the base directory, which is required in order to properly handle symbolic links, we invoke the getCanonicalFile() method.

Then, we execute the relativize() method on the URI object for baseDir, supplying the URI object for file2 as an input, after converting both baseDir and file2 to URI objects using the toURI() function. The relative path between the two paths is represented by the URI object that this method returns.

In order to obtain the relative path as a string and print it, we then execute the getPath() method on the resulting URI object.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription