使用getResourceAsStream在Tomcat中的JAR中加载文件 [英] Loading files in JAR in Tomcat using getResourceAsStream

查看:508
本文介绍了使用getResourceAsStream在Tomcat中的JAR中加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从Tomcat应用程序使用 getResourceAsStream 加载存储在JAR中的文件?

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

我有一个将所需文件放在jar中的库,以及编译的类。当库在独立应用程序中使用时,此代码有效,但在Tomcat中使用库时(使用PHP java-bridge)则不行。

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");

我尝试但没有成功使用问题中概述的解决方案 getResourceAsStream未在webapp中加载资源并将代码更改为

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");

后者代码在独立使用库或在Tomcat中使用库时都不起作用。在这两种情况下 stream == null

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.

我尝试加载的文件正确存储在JAR中 /styles/foo.xsl 。包含所有类和这些其他文件的JAR是 tomcat / webapps / iJavaBridge / WEB-INF / lib /

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/.

有人可以建议一段在Tomcat和非Tomcat应用程序中都有效的代码吗?

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

推荐答案

你需要删除从道路上领先的斜线。这只适用于不在类路径根目录上运行的类加载器。

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");

这篇关于使用getResourceAsStream在Tomcat中的JAR中加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆