简体   繁体   中英

Java Resolve Relative Path

How would 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM