这个问题已经有一个答案在这里:

给我有两个 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));
}

是有一些聪明的方式转换的绝对文件路径相关文件的道路?

可能的重复:

如何构建一个相对路径在java从两个绝对的道路或网址

有帮助吗?

解决方案

这个问题之前 在这里,

这里就是答案,只是在情况下

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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top