Domanda

    

Questa domanda ha già una risposta qui:

         

Dato che ho due File oggetti mi viene in mente la seguente implementazione:

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

C'è un modo più intelligente di conversione di un percorso di file assoluto di un percorso di file relativo?

  

Eventuali duplicati:

     

Come costruire un percorso relativo in java da due percorsi assoluti o URL

È stato utile?

Soluzione

Questa domanda è stato chiesto prima di qui

Ecco la risposta nel caso in cui

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"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top