在jar依赖中读取资源文件

2022-01-15 00:00:00 dependencies resources java jar maven

在我解释我的问题之前 - 我已经尝试在已经提出的问题中找到解决方案,但没有一个起作用;)

Before I explain my problem - I've tried to find solution in already asked questions, but none of them worked ;)

我正在尝试读取 jar 中的文件,这是另一个项目的依赖项.该文件位于路径下

I'm trying to read file inside jar, which is a dependency for another project. This file is located under path

/src/main/resources/driver

项目打包成jar文件.使用 pom 将资源中的 DRIVER 包含到 jar 中:

Project is packaged into jar file. DRIVER from resources is included into jar using pom:

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>*</include>
            </includes>
        </resource>
    </resources>

另外,当我解压 jar 时,我可以看到它已添加到 jar 的根目录中.

Also, when I unpack jar, I can see that it's added to jar's root directory.

我需要做的是将此文件从 jar 内部复制到磁盘上的目录中.只要项目通过 IntelliJ 添加为依赖项目,一切都可以正常工作.当我将它作为 POM 中的依赖项添加时,我得到一个 NullPointerException.

What I need to do, is copy this file from the inside of the jar, to a directory on a disk. It all works fine, as long as the project is added via IntelliJ as a dependent project. When I add it as a dependency in POM, I get a NullPointerException.

我用来加载此文件的代码如下所示:

A code that I use to load this file look like this:

String sourceFilePath = this.getClass().getClassLoader().getResource(driverFileName).getPath();

我也尝试了不同的方法:

I also tried different approaches:

    String sourceFilePath = this.getClass().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getResource("/driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("driver").getPath();
    String sourceFilePath = this.getClass().getClassLoader().getResource("/driver").getPath();

但每次尝试都以相同的结果结束:调用 getPath() 时出现 NullPointerException.

But every try ends with the same result: NullPointerException when calling getPath().

我需要解决方案,因为作为依赖项附加的项目是 UI 测试的框架.到目前为止,我一直在为每个需要它们的新项目添加驱动程序,但这需要时间,这对于想要使用这个框架的人来说变得更加复杂,并且在发布新版本的驱动程序时会带来很多麻烦.我希望能够简单地为这个框架添加一个 maven 依赖项,并能够使用这个框架内部的驱动程序.这里的问题是我需要设置一个带有该驱动程序路径的系统变量.因此,一旦需要驱动程序,我就会尝试将它(代码在框架内)复制到外部位置(某个 tmp 目录).

I need solution for that, because the project that is attached as dependency is a framework for UI tests. Until now I was adding drivers to each new project that needed them, but it takes time, makes it more complicated for people who want to use this framework and makes a lot of trouble when new version of driver is released. I want to be able to simply add a maven dependency for this framework and be able to use drivers from the inside of this framework. The problem here is that I need to set a system variable with path to that driver. So once the driver is needed, I'm trying to copy it (code for that is inside framework) to external location (some tmp directory).

知道怎么解决吗?

推荐答案

像这样使用目标jar类加载器

Use target jar classloader like this

ClassInOtherJar.class.getClassLoader().getResourceAsStream("filename.xml") 

相关文章