1

Is there a way to load files stored inside JARs using getResourceAsStream from Tomcat applications?

I have a library that puts all the files it needs inside its jar, along with the compiled classes. This code works when the library is used in standalone applications but not when the library is used inside Tomcat (using the PHP java-bridge).

final InputStream stream = Object.class.getResourceAsStream("/styles/foo.xsl");

I tried without success to use the solution outlined in question getResourceAsStream not loading resource in webapp and changed the code to

final ClassLoader resourceLoader = Thread.currentThread().getContextClassLoader();
final InputStream stream = resourceLoader.getResourceAsStream("/styles/foo.xsl");

The latter code does not work neither when the library is used standalone or when the library is used in Tomcat. In both cases stream == null.

The file I am trying to load is correctly stored on the JAR in /styles/foo.xsl. The JAR with all the classes and these other files is tomcat/webapps/iJavaBridge/WEB-INF/lib/.

Can someone suggest a piece of code that works both in Tomcat and non-Tomcat applications?

Community
  • 1
  • 1
gioele
  • 9,748
  • 5
  • 55
  • 80
  • http://www.sitepoint.com/forums/showthread.php?320858-tomcat-classloader-problem suggests to use ``. Should I suggest this change to the Tomcat admin? – gioele Oct 16 '11 at 17:26

2 Answers2

6

You need to remove the leading slash from the path. That would only work with classloaders which do not operate on the classpath root.

final ClassLoader resourceLoader = Thread.currentThread().getContextClassLoader();
final InputStream stream = resourceLoader.getResourceAsStream("styles/foo.xsl");
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you, that worked fine. Could you please expand on what do you mean with "classloaders which do not operate on the classpath root"? – gioele Oct 16 '11 at 18:17
  • The classloader which you obtain from some class (as you initially did) operate relative to the location of *that* class and can take a relative path or a path starting with `/`. – BalusC Oct 16 '11 at 18:50
0

if you got a class file in the jar with the xsl try the following: final ClassLoader resourceLoader = com.mypackage.MyClassInJar.class.getClassloader(); final InputStream stream = resourceLoader.getResourceAsStream("/styles/foo.xsl");

if there is no class, just create a dummy class.

i think that should work because you will always get the classloader responsible for the jar.