spoulson
spoulson

Reputation: 21601

How to reference a file in the source dir from any Java code?

Suppose I had a directory containing resource files stored somewhere within the "src" source directory, containing things like templates, config files, etc.

I'm aware that from a Servlet I can access files by name like:

File file = new File(ServletContact.getResource("some/namespace/filename.txt").getPath());

And from a non-Servlet I can do:

File file = new File(Object.class.getResource("some/namespace/filename.txt").getPath());

But the problem is that I have code that needs to access these resource files and can be run independent of the runtime environment. e.g. Some code uses templates from within a servlet (under Tomcat 7). Other code runs as a Quartz background job and works with templates. If I try the Object.class.getResource() method in a Tomcat servlet, it returns null.

How can I access resources files in a safe way regardless of runtime environment, app engine, etc.?

Upvotes: 2

Views: 211

Answers (2)

udalmik
udalmik

Reputation: 7998

To read file from classpath you can use:

getClass().getClassLoader().getResourceAsStream("path/to/resource");

Also there is simple and useful Spring utility ClassPathResource class:

Resource resource = new ClassPathResource("path/to/resource");

Upvotes: 1

Pawel Solarski
Pawel Solarski

Reputation: 1048

I would use any class (e.g. domain class) from your project, use getClassLoader() or getContextClassloader() and provide the path to your resource. Should work.

Upvotes: 1

Related Questions