在Java中将绝对路径转换为相对路径

4

假设我有两个File对象,我可以考虑以下实现:

public File convertToRelative(File home, File file) {
    final String homePath = home.getAbsolutePath();
    final String filePath = file.getAbsolutePath();

    // Only interested in converting file path that is a 
    // direct descendants of home path
    if (!filePath.beginsWith(homePath)) {
        return file;
    }

    return new File(filePath.substring(homePath.length()+1));
}

有没有更聪明的方法将绝对文件路径转换为相对文件路径?

可能是重复问题:

如何从两个绝对路径或URL中构建Java中的相对路径

1个回答

25

这个问题之前曾经被问过,可以在这里找到。

这里是答案,以防万一。

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"

1
好的,那我就关闭这个问题并链接到另一个问题。 - Spoike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接