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

前端 未结 22 2695
小蘑菇
小蘑菇 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 10:45

    It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks 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 note that for file path there's java.nio.file.Path#relativize since Java 1.7, as pointed out by @Jirka Meluzin in the other answer.

提交回复
热议问题