Java Resolve Relative Path
How wou开发者_Python百科ld you go about resolving a relative path? What I am looking for is a function similar to php's realpath. The function just needs to remove all ../ ./ so that the input string can be safely used with other strings.
The general way is to use the File class getCanonicalPath() method.
It's specifically documented to remove (resolve) the ../
and ./
that you're looking for.
Extracts from the docs:
This method first converts this pathname to absolute form if necessary [...] and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
Since you mentioned PHP, I'll assume a web context. With the Servlet API you can get a real path corresponding to a relative path using servletContext.getRealPath(relativePath)
Outside a web context you can use file.getAbsolutePath()
, where file
is java.io.File
constructed with a relative path.
I know it's not in production yet, but in Java 7 one would call Path.resolve(Path).
Just a heads-up.
精彩评论