Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClass().getClassLoader().getResourceAsStream() is caching the resource

I have a resource (velocity template) which I'd like to be able to swap during development. However,

getClass().getClassLoader().getResourceAsStream() 

seems to cache the template. Is there a way to disable this besides using a file loader instead of the class loader?

like image 961
Mike Avatar asked Jun 25 '10 21:06

Mike


People also ask

When using class getResourceAsStream Where will the resource be searched?

The java. lang. Class. getResourceAsStream() finds a resource with a given name.It returns a InputStream object or null if no resource with this name is found.

What is the difference between Class getResource () and ClassLoader getResource ()?

Class. getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

What is getClassLoader in Java?

getClassLoader() is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtual machine dynamically loads classes.

How does getResource work in Java?

The getResource() method of java Class class is used to return the resources of the module in which this class exists. The value returned from this function exists in the form of the object of the URL class.


2 Answers

To avoid caching you can use:

getClass().getClassLoader().getResource().openStream()

It would be equal to using URLResourceLoader for Velocity instead of ClasspathResourceLoader I suppose. I would just go with a file loader.

like image 67
serg Avatar answered Sep 28 '22 08:09

serg


See if something like this helps (exception handling omitted):

URL res = getClass().getClassLoader().getResource(resName);
if (res != null) {
    URLConnection resConn = res.openConnection();
    resConn.setUseCaches(false);
    InputStream in = resConn.getInputStream();
}
like image 28
kschneid Avatar answered Sep 28 '22 08:09

kschneid