Back
Given two absolute paths, e.g.
/var/data/stuff/xyz.dat/var/data
/var/data/stuff/xyz.dat
/var/data
How can one create a relative path that uses the second path as its base? In the example above, the result should be: ./stuff/xyz.dat
It's a short roundabout, but why not apply URI? It has a relativize organization that does all the required tests for you.
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"
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"
Please remark that for file path there's java.nio.file.Path#relativize since
31k questions
32.8k answers
501 comments
693 users