Java 如何使用相对路径获取URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3665484/
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-08-14 03:18:17  来源:igfitidea点击:

how to get URL using relative path

java

提问by Koerr

I have a URL:

我有一个网址:

URL url=new URL("http://www.abc.com/aa/bb/cc/file.html");

and a relative path:

和一个相对路径:

String relativePath="../file2.html"; //maybe is "/file3.html"

I want to get http://www.abc.com/aa/bb/file2.htmlusing variable urland relativePath

我想http://www.abc.com/aa/bb/file2.html使用变量urlrelativePath

How to do it?

怎么做?

采纳答案by Arne Deutsch

new URL(url, relativePath);

回答by Tomas Narros

Try operating winth the class URIinstead of the URL.

尝试使用类URI而不是URL 操作

To get the URI from your URL:

要从您的 URL 获取 URI:

java.net.URI anURI=url.toUri();

Then, to resolve the relative URI:

然后,要解析相对 URI:

URI resultURI=anURI.resolve(relativePath);

And at last, to get an URL type use de method toUrl()of the URI result variable, and you've got it.

最后,要获取 URL 类型,请使用URI 结果变量的方法toUrl(),你就得到了它。

回答by Camilo Díaz Repka

If you want to build an URL pointing to a relative file, you can use:

如果要构建指向相对文件的 URL,可以使用:

URL url = new URL(new URL("file:"), "./myLocalFile.txt");

回答by Jarda

When building relative URL, keep in mind that the base is path to current package, not file. I mean: the referer file is in .../myProject/src/pckg/javafile.javaand the referated file is in .../myProject/some-other/nice.file, then the relative reference should look like this:

在构建相对 URL 时,请记住基础是当前包的路径,而不是文件。我的意思是:引用文件在.../myProject/src/pckg/javafile.java,被引用文件在.../myProject/some-other/nice.file,那么相对引用应该是这样的:

URL url = new URL(new URL("file:"), "./../some-other/nice.file");

and this works for me as well:

这也适用于我:

URL url = new URL("file:./../some-other/nice.file");

回答by Bhabani

This worked for my code
URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");

这适用于我的代码
URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");