Java中的绝对文件路径

Absolute to Relative File Path in Java

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
11
12
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));
}

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

Possible Duplicate:

How to construct a relative path in java from two absolute paths or urls


这个问题以前在这里被问过

这是答案以防万一

1
2
3
4
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"