【问题标题】:Absolute to Relative File Path in Java [duplicate]Java中的绝对相对文件路径[重复]
【发布时间】:2011-01-23 14:31:10
【问题描述】:

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

【问题讨论】:

    标签: java relative-path absolute-path


    【解决方案1】:

    这个问题是在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"
    

    【讨论】:

    • 好的。然后我将关闭问题并链接到另一个问题。
    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 2014-03-14
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2016-11-23
    相关资源
    最近更新 更多