Check whether a path is relative or absolute

11

I would like to know if there is any Java function that checks whether the string is a relative path or not:

Ex:

 
String caminho = funcao("\pasta\arquivo.xml")  // retorna true que é um caminho relativo
String caminho2 = funcao("c:\pasta\arquivo.xml") // retorna false não é caminho relativo

Or if there is already some function that I pass the string it returns me the complete path:

Ex:

String caminho3 = funcao("\pasta\arquivo.xml"); // retorno: c:\pasta\arquivo.xml
String caminho4 = funcao("c:\pasta\arquivo.xml");  // retorno: c:\pasta\arquivo.xml
    
asked by anonymous 21.01.2014 / 14:08

1 answer

11

Check relative path

The method File.isAbsolute() says if the path is absolute. So just deny ( ! ) the return to see if it's relative.

See an example:

File f1 = new File("..");
System.out.println("\"" + f1.getPath() + "\" -> " + f1.isAbsolute());

File f2 = new File("c:\temp");
System.out.println("\"" + f2.getPath() + "\" -> " + f2.isAbsolute());

This will print:

  

".." - > false

     

"c: \ temp" - > true

Recovering the absolute path

To return the full path, use the getAbsolutePath() of an instance of class File .

See another example:

File arquivo1 = new File("\pasta\arquivo.xml");
System.out.println("\"" + arquivo1.getPath() + "\" -> " + arquivo1.getAbsolutePath());

File arquivo2 = new File("c:\pasta\arquivo.xml");
System.out.println("\"" + arquivo2.getPath() + "\" -> " + arquivo2.getAbsolutePath());

This will print:

  

"\ folder \ file.xml" - > C: \ folder \ file.xml

     

"c: \ folder \ file.xml" - > c: \ folder \ file.xml

Note : In Java we do not usually use the term function , we usually call methods since they are always members of classes.     

21.01.2014 / 14:26