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?
From the java.net.url page:
So by leaving off the trailing
/fromlocation, 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.