简体   繁体   English

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

[英]How to get URL using relative path?

I have a URL:我有一个网址:

URL url=new URL("https://example.com/aa/bb/cc/file.html");

and a relative path:和相对路径:

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

I want to get http://example.com/aa/bb/file2.html using variable url and relativePath我想使用变量urlrelativePath获取http://example.com/aa/bb/file2.html

How to do it?怎么做?

new URL(url, relativePath);

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

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

Try operating winth the class URI instead 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 结果变量的 de 方法toUrl() ,你就搞定了。

When building relative URL, keep in mind that the base is path to current package, not file.在构建相对 URL 时,请记住基础是当前包的路径,而不是文件。 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:我的意思是:引用文件在.../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");

我发现有效的是:

new URL("file:./src/gui/Something.fxml")

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

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

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