Home >Java >javaTutorial >How to Generate a Relative Path from Two Absolute Paths in Java?
Creating Relative Paths from Two Absolute Paths
Given two absolute paths, such as:
/var/data/stuff/xyz.dat /var/data
how can we generate a relative path that starts from the second path? For instance, the desired output for the paths above is:
./stuff/xyz.dat
Solution using URI
One approach leverages the URI class, which provides a relativize method to handle such conversions:
String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; // Convert the paths to URIs URI pathURI = new File(path).toURI(); URI baseURI = new File(base).toURI(); // Obtain the relative URI URI relativeURI = pathURI.relativize(baseURI); // Extract the relative path String relativePath = relativeURI.getPath(); // relativePath == "stuff/xyz.dat"
Note: For file paths specifically, Java 1.7 and later offers the relativize method on the java.nio.file.Path interface, as suggested by @Jirka Meluzin.
The above is the detailed content of How to Generate a Relative Path from Two Absolute Paths in Java?. For more information, please follow other related articles on the PHP Chinese website!