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
how to get URL using relative path
提问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.html
using variable url
and relativePath
我想http://www.abc.com/aa/bb/file2.html
使用变量url
和relativePath
How to do it?
怎么做?
采纳答案by Arne Deutsch
new URL(url, relativePath);
回答by Tomas Narros
Try operating winth the class URIinstead of the 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.java
and 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 codeURL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");
这适用于我的代码URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");