views:

88

answers:

2

I want to open files using the class loader. However I always get a FileNotFoundException. How do I create a new File using the URL? I don't want to open it as a stream just as a file.

URL url = VersionUpdater.class.getResource("xslt/screen/foo");
File f = ...
+1  A: 

To convert a file://... URL to java.io.File, you'll have to combine both url.getPath() and url.toURI() for a safe solution:

File f;
try {
    f = new File(url.toURI());
} catch(URISyntaxException e) {
    f = new File(url.getPath());
}

Full explanations in this blog post.

Pascal Thivent
A: 

I'm just thinking: What if foo is in a jar? Then you couldn't construct a File.

It should be possible to make it work, if foo is really in a (local) classpath directory - but you know, it will fail, if someone packages it up in a jar, or loads it via the network...

Chris Lercher