This question already has answers here:
How to construct a relative path in Java from two absolute paths (or URLs)?

(22个答案)


4年前关闭。




给定我有两个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

最佳答案

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"

10-05 19:47