Olek Olkuski
Olek Olkuski

Reputation: 93

Reading resource file inside jar dependency

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

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

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>

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

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

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

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

Any idea how to solve it?

Upvotes: 3

Views: 5889

Answers (2)

jach
jach

Reputation: 153

Use target jar classloader like this

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

Upvotes: 8

Enrique de Miguel
Enrique de Miguel

Reputation: 311

If you want to read a file from inside a jar file, maybe the next line works better:

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

After this you will need to convert the InputStream in to a String. I've used Apache commons IOUtils:

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

I hope it helps...

Upvotes: 0

Related Questions