unj2
unj2

Reputation: 53481

How do I load resource using Class Loader as File?

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

Answers (2)

Chris Lercher
Chris Lercher

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

Pascal Thivent
Pascal Thivent

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

Related Questions