16

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?

Mike
  • 1,176
  • 3
  • 14
  • 26

3 Answers3

8

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.

serg
  • 109,619
  • 77
  • 317
  • 330
  • 1
    Hmmm, didnt work for me... Any idea what else could be causing this? (my code is: `is = getClass().getClassLoader().getResource( mailTemplateFile ).openStream()`) – Lucas Mar 13 '13 at 22:15
  • 1
    This is not properly working as it still caches the resource. Any idea why? – Drubio Jun 25 '18 at 06:10
7

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();
}
kschneid
  • 5,626
  • 23
  • 31
4

Another thing to watch out for (besides the caching mentioned in the other answers) is that your IDE or build system might move your resources to your build directory and put that on the class path. So the file you are editing in your source directory is not the file that is being served.

Chris Vest
  • 8,642
  • 3
  • 35
  • 43