Home >Java >javaTutorial >How Can I Construct a Relative Path from Two Absolute Paths in Java?
Consider the challenge of constructing a relative path from two absolute paths. For instance, given these absolute paths:
/var/data/stuff/xyz.dat /var/data
The desired relative path, with the second path as its base, is:
./stuff/xyz.dat
How can this be achieved effectively in Java?
To solve this problem, consider utilizing Java's URI class. URI provides a method, relativize, which automates the process of creating a relative path based on the provided absolute paths.
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"
If your Java version is 1.7 or later, you can also leverage the relativize method available in java.nio.file.Path.
String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; Path basePath = Paths.get(base); Path absPath = Paths.get(path); Path relativePath = basePath.relativize(absPath); // relativePath == Paths.get("stuff/xyz.dat")
The above is the detailed content of How Can I Construct a Relative Path from Two Absolute Paths in Java?. For more information, please follow other related articles on the PHP Chinese website!