Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading resources loaded by getResourceAsStream

Following best practices, I'm using Thread.currentThread().getContextClassLoader().getResourceAsStream to load resources in a web application (like text files or xml files), instead of going through the file API.

However, this has the disadvantage that if the resource changes on disk, a following call to getResourceAsStream keeps returning the old version indefinitely.

I would like it to pick up the new version though. In my debugger I see there's a simple HashMap called resourceEntries in the classLoader. Using reflection I've been able to remove a specific entry and this seems to work.

This method is however fragile.

Is there a more standard way to do this?

like image 986
akira Avatar asked Jan 20 '11 15:01

akira


People also ask

What does getResourceAsStream return?

The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource.

What is a classpath resource?

A resource is file-like data with a path-like name, which resides in the classpath. The most common use of resources is bundling application images, sounds, and read-only data (such as default configuration). Resources can be accessed with the ClassLoader. getResource and ClassLoader.


2 Answers

Try this:

ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
URL resURL = ctxLoader.getResource(resName);
URLConnection resConn = resURL.openConnection();
resConn.setUseCaches(false);
InputStream resIn = resConn.getInputStream();
...
like image 180
kschneid Avatar answered Nov 02 '22 23:11

kschneid


In addition to kschneid's answer which might work for Tomcat indeed, I wanted to add that for JBoss AS 5+ it already seems to work without needing any special tricks.

Caching of resources is probably class loader specific. The JBoss AS one either doesn't cache or is smart enough to see that the resource on disk has changed.

like image 22
Arjan Tijms Avatar answered Nov 02 '22 23:11

Arjan Tijms