Constructing a Relative Path From Two Absolute Paths in Java

06 May 2023 Balmiki Mandal 0 Core Java

Constructing a Relative Path From Two Absolute Paths in Java

Relative paths are used to refer to files and folders that are located relative to a particular file or folder. Often times, relative paths are used to refer to a particular asset, such as an image, from within a web page. In Java, it is possible to construct a relative path from two absolute paths by using various methods.

Using the URI Class

The most straightforward way to construct a relative path from two absolute paths in Java is to use the java.net.URI class. This class provides a number of useful methods for manipulating URIs. To construct a relative path between two absolute paths, we can use the relativize method provided by this class.

URI uri1 = new URI("/foo/bar/baz");
URI uri2 = new URI("/foo/qux/corge");

URI relativeURI = uri1.relativize(uri2);
System.out.println(relativeURI); // prints: ../../qux/corge

In this example, the relativize method will return the relative path between the two absolute paths. The output of this will be "../../qux/corge".

Using the Paths Class

The java.nio.file.Paths class can also be used to construct a relative path from two absolute paths. This class provides a number of useful methods for manipulating file and directory paths. To construct a relative path between two absolute paths, we can use the relativize method provided by this class.

Path path1 = Paths.get("/foo/bar/baz");
Path path2 = Paths.get("/foo/qux/corge");

Path relativePath = path1.relativize(path2);
System.out.println(relativePath); // prints: ../../qux/corge

In this example, the relativize method will return the relative path between the two absolute paths. The output of this will be "../../qux/corge".

Conclusion

In this article, we discussed how to construct a relative path from two absolute paths in Java. We looked at two different approaches. The first was to use the java.net.URI class, and the second was to use the java.nio.file.Paths class. Both approaches offer a relativize method which is used to construct the relative path between two absolute paths. By using either of these methods, it is possible to construct a relative path from two absolute paths in Java.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.