在jar依赖项中读取资源文件

时间:2017-05-05 07:43:01

标签: java maven jar resources dependencies

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

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

/src/main/resources/driver

项目被打包到jar文件中。来自资源的DRIVER使用pom包含在jar中:

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

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

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

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

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

我也尝试了不同的方法:

    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。

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

知道怎么解决吗?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

如果你想从jar文件中读取文件,也许下一行可以更好地工作:

InputStream in = this.getClass().getResourceAsStream("/driver/filename.txt");

在此之后,您需要将InputStream转换为String。我使用过Apache commons IOUtils:

String theString = IOUtils.toString(inputStream, encoding);

我希望它有所帮助...