Java URL – File gotcha!
November 27, 2006
This one can come up frequently if you’re loading file resources using a ClassLoader. You get a java.net.URL object from the ClassLoader, and you want a java.io.File.
This is wrong: -
File file = new File(url.getFile());
For some reason under windows, URL.getFile() isn’t equivalent to the path of the file. The correct way of getting a file from a URL is: -
File file = new File(url.toURI());
If anyone has any bright ideas of why there isn’t a File(URL) constructor that just takes a URL and barfs if it’s not a file protocol URL, please let me know!