簡體   English   中英

如何使用相對路徑獲取 URL?

[英]How to get URL using relative path?

我有一個網址:

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

和相對路徑:

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

我想使用變量urlrelativePath獲取http://example.com/aa/bb/file2.html

怎么做?

new URL(url, relativePath);

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

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

嘗試使用類URI而不是URL進行操作。

要從您的 URL 獲取 URI:

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

然后,解析相對 URI:

URI resultURI=anURI.resolve(relativePath);

最后,要獲得一個 URL 類型,使用 URI 結果變量的 de 方法toUrl() ,你就搞定了。

在構建相對 URL 時,請記住基礎是當前包的路徑,而不是文件。 我的意思是:引用文件在.../myProject/src/pckg/javafile.java和被引用文件在.../myProject/some-other/nice.file ,那么相對引用應該是這樣的:

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

這也適用於我:

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