Reading resource file inside jar dependency
dependencies, jar, java, maven, resources
Solution
Use target jar classloader like this
ClassInOtherJar.class.getClassLoader().getResourceAsStream("filename.xml")
Problem
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?