Beginner Beginner - 3 months ago 30
Java Question

Build relative path between two file path

I would like to compare two paths in the same workspace folder, and get the relative path between them :

String firPath = "C:/toto/tata/test1/test2/img/1.jpg" // test example
String secPath = "C:/toto/tata/test1/img/1.jpg" // test example

And return firstPath relative path from secondPath

example = "../../img/"

I found lots of example in different language (python, .net, c++ ...) :

How to get relative path from absolute path

compare path and get relative path between two files with javascript

...but no solution with java.

Most of the time, what is use are libraries methods, and I was wondering if java had the same methods I could use.

Thank you for your help.


What about added in Java 7 Path.relativize?

Path first = Paths.get(firstPath); Path second = Paths.get(secondPath);