Created
February 7, 2013 09:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
The behaviour of URL vs URI seems messy and inconsistent, I guess they have to keep it that way though for backward compatibility reasons...
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
use instead
String filename = url.toURI().getPath();