Reputation: 197
I've encountered a bug in a library my application is using. I've narrowed the issue down to the behavior of the java.net.URL
class and how the library uses it to look up resources.
When I run the following code, the output is file:/root/myfile.xml
instead of file:/root/folder/myfile.xml
.
public static void main(String[] args) throws MalformedURLException {
String location = "file:///root/folder";
String spec = "myfile.xml";
URL context = new URL(location);
URL url = new URL(context, spec);
System.out.println(url);
}
I get the expected output if I append a slash to location
.
I'm curious, why does java.net.URL
behave like this?
Upvotes: 1
Views: 112
Reputation: 11381
From the java.net.url page:
An application can also specify a "relative URL", which contains only enough information to reach the resource relative to another URL. Relative URLs are frequently used within HTML pages. For example, if the contents of the URL:
http://java.sun.com/index.html
contained within it the relative URL:
FAQ.html
it would be a shorthand for:
http://java.sun.com/FAQ.html
So by leaving off the trailing /
from location
, you're not specifying to the URL constructor that it is the root for the spec, rather than a relative path to be joined with.
Upvotes: 3