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 object from the ClassLoader, and you want a

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!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: