Reputation: 53481
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 = ...
Upvotes: 4
Views: 2055
Reputation: 37778
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...
Upvotes: 0
Reputation: 570315
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.
Upvotes: 3