简体   繁体   English

Java解析相对路径

[英]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.我正在寻找的是一个类似于 php 的 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.一般的方法是使用 File 类的getCanonicalPath()方法。
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).和路径名中的“..” ,解析符号链接(在 UNIX 平台上),并将驱动器号转换为标准大小写(在 Microsoft Windows 平台上)。

Since you mentioned PHP, I'll assume a web context.既然你提到了 PHP,我将假设一个网络上下文。 With the Servlet API you can get a real path corresponding to a relative path using servletContext.getRealPath(relativePath)使用 Servlet API,您可以使用servletContext.getRealPath(relativePath)获得与相对路径相对应的真实路径

Outside a web context you can use file.getAbsolutePath() , where file is java.io.File constructed with a relative path.在 Web 上下文之外,您可以使用file.getAbsolutePath() ,其中file是使用相对路径构造的java.io.File

I know it's not in production yet, but in Java 7 one would call Path.resolve(Path) .我知道它还没有投入生产,但在 Java 7 中,人们会调用Path.resolve(Path)

Just a heads-up.只是一个提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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