Check whether a path is relative or absolute

Asked

Viewed 1,892 times

11

I wonder if there is a 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 also 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

1 answer

11


Check relative path

The method File.isAbsolute() says if the path is absolute. Then just deny (!) the return to know if it is relative.

Take 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 method getAbsolutePath() of a class instance File.

See one more 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.xml file" -> C: folder.xml file

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


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

  • Disagreeing with its final note. It seems to say that a function can only be called a function if the language has first-class functions.

  • 1

    @What I meant was that in Java it is not called a function method. A function, in my opinion, is any procedure that remains in the overall scope, in any namespace or lib, but Java doesn’t have that. But really a language can have functions or procedures without them being first-class.

  • I don’t really know Java in practice... but I always thought that anything that returns a result would be called a function. Those who do not return from method, and both would be procedures.

  • @Miguelangelo See this question in the SOEN: http://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function

  • I ended up asking a question here at SOPT... but there’s a very interesting material in this SOEN answer. It was wrong to pollute so much this answer... should have asked the question before. You think I should delete the comments?

  • @Miguelangelo I don’t think you need to delete, there are no other comments.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.