给定以下代码:
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 对象的路径中移动超过两 (2) 个“../”相对目录时,看起来 URL 类正在删除部分路径,当我使用
URL(URL, String)
构造函数,部分路径在构造过程中被删除。我尝试在文件之后使用“//” :在 URL 中,但它没有任何区别。
难道我做错了什么?或者这只是按设计工作?如果是这样,是否可以在不首先使用 URL 对象的getPath或getFile 方法对其进行解构的情况下附加/替换 URL 的文件部分?
这不是我使用的构造函数的设计目的吗?
我检查了 Java 跟踪:http ://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html 它说:
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");
所以看来我正在按预期使用它。