2010-03-04 52 views
2

相對文件路徑假設我有兩個File對象,我能想到以下實現的:絕對在Java

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

回答

17

有人問這個問題之前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" 
+1

所有權利。我會結束這個問題,並鏈接到另一個問題。 – Spoike 2010-03-04 09:56:34