Constructing Relative Paths from Absolute Paths in Java
When working with absolute paths in Java, there may be instances where you need to create a relative path based on another absolute path. This article demonstrates how to achieve this using the URI class and its relativize method.
Consider the following two absolute paths:
/var/data/stuff/xyz.dat /var/data
To create a relative path that uses the second path as its base, follow these steps:
Here is an example code snippet:
String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath(); // relative == "stuff/xyz.dat"
This code will produce a relative path of "stuff/xyz.dat", which is the desired result.
It's worth noting that for file paths, Java 1.7 introduced the Path#relativize method, which can also be used for this purpose.
The above is the detailed content of How to Construct Relative Paths from Absolute Paths in Java?. For more information, please follow other related articles on the PHP Chinese website!