代码之家  ›  专栏  ›  技术社区  ›  Spoike Otávio Décio

Java中相对文件路径的绝对值[复制]

  •  2
  • Spoike Otávio Décio  · 技术社区  · 15 年前

    如果我有两个 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 回复  |  直到 15 年前
        1
  •  20
  •   Community CDub    8 年前

    这个问题以前被问过 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"