问题
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?
回答1:
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");
回答2:
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.
来源:https://stackoverflow.com/questions/7785973/loading-files-in-jar-in-tomcat-using-getresourceasstream