Pure Danger Tech


Files and URLs

10 Apr 2008

I was working on some stuff today that converts between File and URL and someone pointed out that the “obvious” ways to convert between them in the JDK are kind of broken with respect to urls/paths with spaces in them.

The obvious way to get from a File to a URL is with File.toURL(). However, the javadoc for this method notes that it does not automatically escape characters that are illegal in URLs (like spaces to %20). In fact, you’ll note that newly in JDK 1.6, this method is actually deprecated. They recommend to instead do file.toURI().toURL().

Going the other way, it’s quite tempting to do URL.getPath() (assuming you already know you’re dealing with a file:// url). But in this case, the escape characters are not properly undone – spaces are the most common issue. Here, Apache Commons IO has a FileUtils class that can come in handy, in particular the toFile() method.

Commons IO also has a helper for converting Files to URLs but the code there seems to be erroneously using the same bad File.toURL(), so you might want to stay away from that and use the toURI().toURL() technique above. I logged this at Apache as IO-163.