如何从JAR

时间:2017-09-30 09:20:18

标签: java classloader

文件结构:

/web-project
   |
   |---/WEB-INF/a.jar
   |
   |---/META-INF/resources/b.properties
位于A.class

a.jar想要阅读/META-INF/resources/b.properties

我认为a.jar和b.properties都在同一个类加载器下(因为它们位于同一个Web上下文中)

我尝试过以下方法来达到目的,但没有成功。

InputStream is = null;
ClassLoader[] loaders = { Thread.currentThread().getContextClassLoader(),
    ClassLoader.getSystemClassLoader(), getClass().getClassLoader() };

ClassLoader currentLoader = null;
for (int i = 0; i < loaders.length; i++) {
    if (loaders[i] != null) {
        currentLoader = loaders[i];
        is = currentLoader.getResourceAsStream("/META-INF/resources/b.properties");
        if (is != null) { // is is always null no matter what ways I used.
            break;
        }
    }
}

我不知道我在哪里犯错。 请引导我走正确的道路。 非常感谢你。

=====修订=====

首先,感谢所有评论,回答和讨论这个问题的人(特别是@Ravi&amp; @EJP)。

以下是我根据讨论尝试的内容。

InputStream is = null;
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
is = A.class.getClassLoader().getResourceAsStream(url.getPath() + "../../../META-INF/resources/b.properites"); // is = null
is = new FileInputStream(url.getPath() + "../../../META-INF/resources/b.properites"); // is != null

我似乎应该使用FileInputStream来获取JAR之外的资源,而不是使用getResourceAsStream()

=====更新2 =====

最终,我通过以下解决方案找到了它。

context.getResourceAsStream("/META-INF/resources/b.properties");

基于以下先决条件:

a.jar / b.properties在同一个上下文中

A.class可以获取ServletContext对象

2 个答案:

答案 0 :(得分:1)

首先验证jar文件的路径,可以解决此问题。您可以执行以下代码行并检查路径

 getClass().getProtectionDomain().getCodeSource().getLocation();

由于您的资源文件位于jar文件之外,因此您需要将路径 relative 更改为您的jar文件。

Properties mainProperties = new Properties();
FileInputStream file = new FileInputStream("<relative-path>/META-INF/resources/b.properties");
mainProperties.load(file);
file.close();

我已经使用以下文件夹结构测试了上面的代码

/web-project
   |
   |---/WEB-INF/a.jar
   |
   |---/test/resources/b.properties

答案 1 :(得分:1)

  

我似乎应该使用FileInputStream来获取JAR之外的资源,而不是使用getResourceAsStream()

根据定义,资源是 JAR文件中。除此之外的任何内容都不是资源而是文件,您应该使用FileInputStreamFileReader来阅读它。你可以使用

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();

获取JAR文件的位置,因此如果您将文件分发到同一目录中,则只需要进行一些路径修改即可从中获取文件的路径。 / p>