Programa Java para obter o caminho relativo de dois caminhos absolutos

Neste exemplo, aprenderemos a obter o caminho relativo de dois caminhos absolutos em Java usando métodos String, classe URI e pacote java.nio.file.

Exemplo 1: obtenha um caminho relativo de dois caminhos absolutos usando a classe URI

 import java.io.File; import java.net.URI; class Main ( public static void main(String() args) ( try ( // Two absolute paths File absolutePath1 = new File("C:\Users\Desktop\Programiz\Java\Time.java"); System.out.println("Absolute Path1: " + absolutePath1); File absolutePath2 = new File("C:\Users\Desktop"); System.out.println("Absolute Path2: " + absolutePath2); // convert the absolute path to URI URI path1 = absolutePath1.toURI(); URI path2 = absolutePath2.toURI(); // create a relative path from the two paths URI relativePath = path2.relativize(path1); // convert the URI to string String path = relativePath.getPath(); System.out.println("Relative Path: " + path); ) catch (Exception e) ( e.getStackTrace(); ) ) )

Resultado

 Caminho absoluto1: C: Usuários Desktop Programiz Java Time.java Caminho absoluto2: C: Usuários Caminho relativo do desktop: Programiz / Java / Time.java

No exemplo acima, temos dois caminhos absolutos chamados absolutePath1 e absolutePath2. Usamos a classe URI para converter os caminhos absolutos no caminho relativo.

  • toURI () - converte o Fileobjeto em um Uri
  • relativize () - extrai o caminho relativo comparando dois caminhos absolutos um com o outro
  • getPath () - converte o Uri em uma string

Leitura recomendada :

  • Arquivo Java
  • Classe URI Java

Exemplo 2: obtenha um caminho relativo de dois caminhos absolutos usando métodos String

 import java.io.File; class Main ( public static void main(String() args) ( // Create file objects File file1 = new File("C:\Users\Desktop\Programiz\Java\Time.java"); File file2 = new File("C:\Users\Desktop"); // convert file objects to string String absolutePath1 = file1.toString(); System.out.println("Absolute Path1: " + absolutePath1); String absolutePath2 = file2.toString(); System.out.println("Absolute Path2: " + absolutePath2); // get the relative path String relativePath = absolutePath1.substring(absolutePath2.length()); System.out.println("Absolute Path: " + relativePath); ) )

Resultado

 Caminho absoluto1: C: Usuários Desktop Programiz Java Time.java Caminho absoluto2: C: Usuários Caminho absoluto da área de trabalho: Programiz Java Time.java

No exemplo acima, convertemos os caminhos dos arquivos em strings. Observe a expressão,

 absolutePath1.substring(absolutePath2.length())

Aqui, o substring()método retorna a parte de absolutePath1 começando do índice igual ao comprimento de absolutePath2. Ou seja, a string representada por absolutePath2 é removida de absolutePath1.

Para saber mais sobre como a substring funciona, visite Java String substring ().

Exemplo 3: obtenha um caminho relativo de dois caminhos absolutos usando o pacote java.nio.file

 import java.nio.file.Path; import java.nio.file.Paths; class Main ( public static void main(String() args) ( // Create file objects Path absolutePath1 = Paths.get("C:\Users\Desktop\Programiz\Java\Time.java"); Path absolutePath2 = Paths.get("C:\Users\Desktop"); // convert the absolute path to relative path Path relativePath = absolutePath2.relativize(absolutePath1); System.out.println("Relative Path: " + relativePath); ) )

Resultado

 Relative Path: ProgramizJavaTime.java

No exemplo acima, usamos o relativize()método da Pathinterface para obter um caminho relativo de dois caminhos absolutos.

Leituras recomendadas :

  • Classe de caminhos Java
  • Interface Java Path

Artigos interessantes...