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

前端 未结 22 2769
小蘑菇
小蘑菇 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:49

    If you know the second string is part of the first:

    String s1 = "/var/data/stuff/xyz.dat";
    String s2 = "/var/data";
    String s3 = s1.substring(s2.length());
    

    or if you really want the period at the beginning as in your example:

    String s3 = ".".concat(s1.substring(s2.length()));
    

提交回复
热议问题