vdenotaris
vdenotaris

Reputation: 13637

Instancing a java.io.File to read a resource from classpath

Supposing that I've a project structure as follows:

+ src
---+ main
------+ java
------+ resources

How can I define a java.io.File instance that is able to read an xml from resources folder?

Upvotes: 1

Views: 1039

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109613

No, use an InputStream, with the path starting under resources.

InputStream in = getClass().getResourceAsStrem("/.../...");

Or an URL

URL url = getClass().getResource("/.../...");

This way, if the application is packed in a jar (case sensitive names!) it works too. The URL in that case is:

"jar:file://... .jar!/.../..."

If you need the resource as file, for instance to write to, you will need to copy the resource as initial template to some directory outside the application, like System.getProperty("user.home").

Path temp = Files.createTempFile("pref", "suffix.dat");
Files.copy(getClass().getResourceAsStream(...), temp, StandardCopyOption.REPLACE_EXISTING);
File file = temp.toFile();

As @mjaggard commented, createTempFile creates an empty file, so Files.copy will normally fail unless with option REPLACE_EXISTING.

Upvotes: 0

William Morrison
William Morrison

Reputation: 11006

It depends on what your program's working directory is.

You can get your working directory at runtime via System.getProperty("user.dir");

Here's a link with more info

Once you've got that, create a relative filepath pointing to your resource folder.

For example, if your working directory is src, create a relative filepath like so:

new File(Paths.get("main","resources").toString());

There are weaknesses with this approach as the actual filepath you use may change when you deploy your application, but it should get you through some simple development.

Upvotes: 1

Related Questions