Pergunta

Dado eu tenho dois File Objetos que consigo pensar na seguinte implementação:

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

Existe uma maneira mais inteligente de converter um caminho de arquivo absoluto em um caminho de arquivo relativo?

Possível duplicata:

Como construir um caminho relativo em Java a partir de dois caminhos ou URLs absolutos

Foi útil?

Solução

Esta pergunta foi feita antes aqui

Aqui está a resposta apenas no caso

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"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top