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

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

    Here a method that resolves a relative path from a base path regardless they are in the same or in a different root:

    public static String GetRelativePath(String path, String base){
    
        final String SEP = "/";
    
        // if base is not a directory -> return empty
        if (!base.endsWith(SEP)){
            return "";
        }
    
        // check if path is a file -> remove last "/" at the end of the method
        boolean isfile = !path.endsWith(SEP);
    
        // get URIs and split them by using the separator
        String a = "";
        String b = "";
        try {
            a = new File(base).getCanonicalFile().toURI().getPath();
            b = new File(path).getCanonicalFile().toURI().getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] basePaths = a.split(SEP);
        String[] otherPaths = b.split(SEP);
    
        // check common part
        int n = 0;
        for(; n < basePaths.length && n < otherPaths.length; n ++)
        {
            if( basePaths[n].equals(otherPaths[n]) == false )
                break;
        }
    
        // compose the new path
        StringBuffer tmp = new StringBuffer("");
        for(int m = n; m < basePaths.length; m ++)
            tmp.append(".."+SEP);
        for(int m = n; m < otherPaths.length; m ++)
        {
            tmp.append(otherPaths[m]);
            tmp.append(SEP);
        }
    
        // get path string
        String result = tmp.toString();
    
        // remove last "/" if path is a file
        if (isfile && result.endsWith(SEP)){
            result = result.substring(0,result.length()-1);
        }
    
        return result;
    }
    

提交回复
热议问题