Java中绝对到相对文件路径

Java中绝对到相对文件路径,java,relative-path,absolute-path,Java,Relative Path,Absolute Path,鉴于我有两个文件对象,我可以想到以下实现: 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 // dire

鉴于我有两个
文件
对象,我可以想到以下实现:

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));
}
是否有更聪明的方法将绝对文件路径转换为相对文件路径

可能重复:


这个问题以前被问过

这是以防万一的答案

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"

好吧然后我将关闭该问题并链接到另一个问题。