2010-03-04 3 views
2

Étant donné que j'ai deux File objets que je peux penser à la mise en œuvre suivante:absolu de chemin de fichier relatif en 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)); 
} 

est-il une façon plus intelligente de la conversion d'un chemin de fichier absolu à un chemin de fichier relatif?

Possible en double:

How to construct a relative path in java from two absolute paths or urls

Répondre

17

Cette question a été posée avant here

Voici la réponse juste au cas où

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

bien. Je vais donc fermer la question et faire un lien vers l'autre question. – Spoike

Questions connexes