Fix incorrect usage of method "URL#getFile()"

Steps to reproduce

The method "URL#getFile()" is possible the worst named method in the whole Java API. While the name seems seems to be clear enough, it is seldom what one really expects and/or wants: it returns the URL path *plus the query string, concatenated, if there is any*. That means that, for a URL like:

, the method "getFile" will return:


, which has very little use for most purposes.

On the other hand, the URL class does not decode its contents, which means that a path with special characters such as spaces (e.g. "path to resource/resource.txt") will be represented as:

For this URL, "getFile()" would return:


, which needs to be decoded before we can use it to compose a filesystem path, for instance. This decoding step is very often forgotten.

The method is particularly misused the code needs to read a resource from the current classloader, typical through the construction:


returning a URL, which for most purposes is not very convenient and should be converted to a File. The canonical (correct) method to do so would be:

new File(MyClass.class.getResource("/myResource").toURI());

, which has two problems: the File(URI) constructor throws IllegalArgumentException while the "URL#toURI()" method throws URISyntaxException. Handlling these is annoying. On the other hand, something like:

new File(MyClass.class.getResource("/myResource").getFile());

does not throw any exception, because "URL#getFile()" throws no exceptions and, because it returns a String, the constructor "File(String)" is used instead, which also does not throw an exception. However, it only works provided that a) the URL has no query string; and b) the URL path contains only non-url-encoded characters.

In most cases, the path(s) where Opencast run do not contain special characters, and the URLs do not contain query strings. However, should some of this conditions occur, the build or even a running system may yield unexpected results, which are relatively difficult to triage.

Fixed and reviewed


Rubén Pérez


Rubén Pérez


Incorrectly Functioning Without Workaround