4

I have a Spring Web Application which was created as a maven artifact A.war. It has a maven dependency with a artifact B.jar. The src/main/resources of artifact B has a file test.txt. I want to read the file test.txt from artifact A.war. When i explode the B.jar, i see that the test.txt is located in the root of the jar. The B.jar ends up in WEB-INF/lib of the exploded A.war In A, i try to read the file using File f = new ClassPathResource("test.txt").getFile();

I am getting java.io.FileNotFoundException: class path resource [test.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:B.jar!/test.txt. I also tried File f = new File(getClass().getResource("test.txt").toURI());

Could someone please help?

kaputabo
  • 343
  • 1
  • 3
  • 12

2 Answers2

6

I finally got it to work by following an alternate path mentioned in link

Basically in the pom file of Artifact A, I used the maven dependency plugin and unpack goal. Using that, I unpacked the artifact B and copied the test.txt to the target/classes directory of project A.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>com.me</groupId>
                                <artifactId>artifactB</artifactId>
                                <version>1.0-SNAPSHOT</version>
                                <outputDirectory>${basedir}/target/classes</outputDirectory>
                                <includes>*.txt,*.xml</includes>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

On taking the build of artifact A, the war file A.war is created and the test.txt appears in the WEB-INF/classes directory of the exploded war file, so it's in the classpath.

kaputabo
  • 343
  • 1
  • 3
  • 12
-1

You have to build an own class loader for the classpath resource to read files from jars.

I explained it in my blog post (https://skmit.wordpress.com/2012/02/29/read-classpath-resource-from-jar-files-with-spring/)

Sandra Parsick
  • 704
  • 7
  • 14