给出两条绝对路径,例如

/var/data/stuff/xyz.dat
/var/data

如何创建一个以第二条路径为基础的相对路径?在上面的例子中,结果应该是:./stuff/xyz.dat


当前回答

如果你正在编写一个Maven插件,你可以使用Plexus的PathTool:

import org.codehaus.plexus.util.PathTool;

String relativeFilePath = PathTool.getRelativeFilePath(file1, file2);

其他回答

在另一个答案中提到的错误是由Apache HttpComponents中的URIUtils解决的

public static URI resolve(URI baseURI,
                          String reference)

对象的URI引用 基本URI。解决bug的方法 java.net.URI ()

我知道这有点晚了,但是,我创建了一个解决方案,适用于任何java版本。

    public static String getRealtivePath(File root, File file) 
    {
        String path = file.getPath();
        String rootPath = root.getPath();
        boolean plus1 = path.contains(File.separator);
        return path.substring(path.indexOf(rootPath) + rootPath.length() + (plus1 ? 1 : 0));
    }

如果你知道第二个字符串是第一个字符串的一部分:

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

或者,如果你真的想把句号放在开头,就像你的例子中那样:

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

Psuedo-code:

使用路径分隔符("/")拆分字符串 通过迭代拆分字符串的结果来找到最大的公共路径(因此在两个示例中,您最终会得到"/var/data"或"/a") 返回“。”+ whicheverPathIsLonger.substring (commonPath.length);

如果你正在编写一个Maven插件,你可以使用Plexus的PathTool:

import org.codehaus.plexus.util.PathTool;

String relativeFilePath = PathTool.getRelativeFilePath(file1, file2);