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

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

    private String relative(String left, String right){
        String[] lefts = left.split("/");
        String[] rights = right.split("/");
        int min = Math.min(lefts.length, rights.length);
        int commonIdx = -1;
        for(int i = 0; i < min; i++){
            if(commonIdx < 0 && !lefts[i].equals(rights[i])){
                commonIdx = i - 1;
                break;
            }
        }
        if(commonIdx < 0){
            return null;
        }
        StringBuilder sb = new StringBuilder(Math.max(left.length(), right.length()));
        sb.append(left).append("/");
        for(int i = commonIdx + 1; i < lefts.length;i++){
            sb.append("../");
        }
        for(int i = commonIdx + 1; i < rights.length;i++){
            sb.append(rights[i]).append("/");
        }
    
        return sb.deleteCharAt(sb.length() -1).toString();
    }
    

提交回复
热议问题