2010-09-08 46 views
21

我有一个网址:怎样用URL相对路径

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

和相对路径:

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

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

如何做它?

回答

47
new URL(url, relativePath); 
+1

+1。有关Java API的更多详细信息:http://download.oracle.com/javase/6/docs/api/java/net/URL.html – 2010-09-08 07:46:34

+0

谢谢,但它只在JDK6中:( – Koerr 2010-09-08 07:53:26

+0

不,该方法自1.0 。这里至少有1.3的文档(找不到1.0;)。http://download.oracle.com/javase/1.3/docs/api/java/net/URL.html#URL%28java.net.URL, %20java.lang.String%29 – Arne 2010-09-08 08:01:12

9

尝试winth类URI而不是URL操作。

从您的网址得到URI:

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

然后,解决了相对URI:

URI resultURI=anURI.resolve(relativePath); 

,最后,得到一个URL类型使用德法的toURL() URI结果变量的,你已经知道了。

+5

为什么使用URI比URL更好? – sixtyfootersdude 2010-10-11 16:46:56

7

如果你想建立指向相对文件的URL,你可以使用:

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

当建立相对URL,记住该基地是目前包路径,而不是文件。我的意思是:引荐文件是.../myProject/src/pckg/javafile.java和referated文件为.../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"); 
-1

这个工作代码
URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");