给出以下代码:
class testurl
{
public void test()
{
try {
URL url1 = new URL("file:../../foo/bar/");
URL url2 = new URL(url1, "file.txt");
URL url3 = new URL("file:../../../../foo/bar/");
URL url4 = new URL(url3, "file.txt");
URL url5 = new URL("file:../../../../../foo/bar/");
URL url6 = new URL(url5, "file.txt");
System.out.println("url1: " + url1.toString());
System.out.println("url2: " + url2.toString());
System.out.println("url3: " + url3.toString());
System.out.println("url4: " + url4.toString());
System.out.println("url5: " + url5.toString());
System.out.println("url6: " + url6.toString());
}
catch (MalformedURLException ex) {
System.out.println("MalformedURLException Exception:");
System.out.println(ex);
}
}
public static void main(String[] args)
{
testurl obj = new testurl();
obj.test();
}
}
我看到以下输出:
url1: file:../../foo/bar/
url2: file:../../foo/bar/file.txt
url3: file:../../../../foo/bar/
url4: file:../../foo/bar/file.txt
url5: file:../../../../../foo/bar/
url6: file:../foo/bar/file.txt
当我使用 构造函数,在构造期间删除路径的一部分。我尝试在网址中的文件:之后使用'//',但它没有任何区别。 我做错了吗?或者这只是按设计工作?
如果是这样,是否可以追加/替换URL的文件部分
不首先使用 getPath 或 getFile 解构它
URL对象的方法? 这不是我正在使用的构造函数的目的吗? 我检查了Java跟踪:http://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html
它说: 所以看来我正在按预期使用它。URL(URL, String)
You can create URL objects for these pages relative to their common base
URL:http://example.com/pages/ like this:
URL myURL = new URL("http://example.com/pages/");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");