Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

Given two absolute paths, e.g.

/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

1 Answer

0 votes
by (46k points)

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"

Please remark that for file path there's java.nio.file.Path#relativize since 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Jul 11, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer

Browse Categories

...