在两个文件路径之间建立相对路径

Build relative path between two file path

我想比较同一个工作区文件夹中的两个路径,并得到它们之间的相对路径:

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

和return firstPath相对于secondPath的相对路径

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

我发现了很多不同语言的示例(python、.net、c++ ...):

How to get relative path from absolute path

compare path and get relative path between two files with javascript

...但 java.

没有解决方案

大多数时候,使用的是库方法,我想知道 java 是否有我可以使用的相同方法。

感谢您的帮助。

在 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));