java Java解析相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5121967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:33:43  来源:igfitidea点击:

Java Resolve Relative Path

java

提问by Pass

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.

您将如何解决相对路径?我正在寻找的是一个类似于 php 的 realpath 的函数。该函数只需要删除所有 ../ ./ 以便输入字符串可以安全地与其他字符串一起使用。

回答by Stephen P

The general way is to use the File class getCanonicalPath()method.

一般的方法是使用 File 类的getCanonicalPath()方法。

回答by Bozho

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)

既然你提到了 PHP,我将假设一个网络上下文。使用 Servlet API,您可以获得与使用相对路径相对应的真实路径servletContext.getRealPath(relativePath)

Outside a web context you can use file.getAbsolutePath(), where fileis java.io.Fileconstructed with a relative path.

在 Web 上下文之外,您可以使用file.getAbsolutePath(), wherefilejava.io.File用相对路径构造的。

回答by Steve Emmerson

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.

只是一个提示。