Skip to content

Instantly share code, notes, and snippets.

@purplefox
Created February 7, 2013 09:30
Show Gist options
  • Save purplefox/4729823 to your computer and use it in GitHub Desktop.
Save purplefox/4729823 to your computer and use it in GitHub Desktop.
Possible bug in JDK URL class? Certainly the behaviour seems odd. I would expect URL.getFile() to url unencode the url.
// Make sure you have a directory which has a space in it's name, e.g:
File f = new File("/home/tim/dir foo/foo.txt");
System.out.println("exists?" + f.exists()); // 'exists?true'
// Convert it to a file URL
URL url = f.toURI().toURL();
System.out.println("url is:" + url); // 'url is:file:/home/tim/dir%20foo/foo.txt' - space has been correctly URL encoded
// Now convert the url back to a file name
String filename = url.getFile();
System.out.println("f2 is:" + filename); // 'f2 is:/home/tim/dir%20foo/foo.txt' - whoops hasn't been url unencoded
File f2 = new File(filename);
System.out.println("exists?" + f2.exists()); // 'exists?false' - ouch
@jmesnil
Copy link

jmesnil commented Feb 7, 2013

use instead

String filename = url.toURI().getPath();

@purplefox
Copy link
Author

The behaviour of URL vs URI seems messy and inconsistent, I guess they have to keep it that way though for backward compatibility reasons...

@vjanelle
Copy link

vjanelle commented Feb 7, 2013

URLs and URIs are different things though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment