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

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

    Psuedo-code:

    1. Split the strings by the path seperator ("/")
    2. Find the greatest common path by iterating thru the result of the split string (so you'd end up with "/var/data" or "/a" in your two examples)
    3. return "." + whicheverPathIsLonger.substring(commonPath.length);

提交回复
热议问题