Question

    

Cette question a déjà une réponse ici:

         

Étant donné que j'ai deux objets File je peux penser à la mise en œuvre suivante:

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));
}

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

  

Possible en double:

     

Comment la construction d'un chemin relatif en java à partir de deux chemins absolus ou URL

Était-ce utile?

La solution

a posé cette question ici

Voici la réponse juste au cas

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"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top