Java中相对文件路径的绝对

时间:2010-03-04 09:42:54

标签: java relative-path absolute-path

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

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

  

可能重复:

     

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

1 个答案:

答案 0 :(得分:21)

here

之前询问了这个问题

以下是答案

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"
相关问题