How to construct a relative path in Java from two absolute paths (or URLs)?

前端 未结 22 2744
小蘑菇
小蘑菇 2020-11-22 10:30

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?

22条回答
  •  清歌不尽
    2020-11-22 11:03

    Here is a solution other library free:

    Path sourceFile = Paths.get("some/common/path/example/a/b/c/f1.txt");
    Path targetFile = Paths.get("some/common/path/example/d/e/f2.txt"); 
    Path relativePath = sourceFile.relativize(targetFile);
    System.out.println(relativePath);
    

    Outputs

    ..\..\..\..\d\e\f2.txt
    

    [EDIT] actually it outputs on more ..\ because of the source is file not a directory. Correct solution for my case is:

    Path sourceFile = Paths.get(new File("some/common/path/example/a/b/c/f1.txt").parent());
    Path targetFile = Paths.get("some/common/path/example/d/e/f2.txt"); 
    Path relativePath = sourceFile.relativize(targetFile);
    System.out.println(relativePath);
    

提交回复
热议问题