Getting Relative Paths from Absolute URLs in Java
When working with paths in Java, it's often necessary to convert absolute paths into relative paths with respect to a specified base path. This can be achieved using the relativize() method provided by the java.net.URI class.
Consider the example paths:
/var/data/stuff/xyz.dat /var/data
To create a relative path using the latter path as its base, you can do the following:
String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
This code converts the absolute paths to URIs, performs the relativization, and extracts the resulting path. The output will be:
stuff/xyz.dat
Please note that for file paths specifically, Java 1.7 introduced the relativize() method in the java.nio.file.Path class. You can utilize this method for a more efficient solution if you are working with file paths.
The above is the detailed content of How to Get Relative Paths from Absolute URLs in Java?. For more information, please follow other related articles on the PHP Chinese website!