Loading files in JAR in Tomcat using getResourceAsStream

戏子无情 提交于 2019-12-13 17:43:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!