Beginner
Beginner

Reputation: 171

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.

Upvotes: 7

Views: 5345

Answers (1)

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

What about added in Java 7 Path.relativize?

Path first = Paths.get(firstPath); Path second = Paths.get(secondPath);
System.out.println(first.relativize(second)); 
System.out.println(second.relativize(first)); 

Upvotes: 14

Related Questions