How to read file from file system during Maven build of module

Kjeld :

I have a Maven project A (packaged as a pom) containing Maven module project B (packaged as a jar). Project B is also physically in the root of project A.

When B is being built, a plugin indirectly uses my code (inside B) to access a property file in its src/main/resources location.

When I build project B directly (mvn clean install) the code can easily find that file by using new File("src/main/resources/foo.properties");

However when I try to build project A, it first will try to build the module B, and in that case it cannot find the property file.

Apart from the 'new File' variant, I have tried using this.getClass().getClassLoader().getResourceAsStream("src/main/resources/foo.properties");

and I tried using Spring:

Resource resource = new ClassPathResource("src/main/resources/foo.properties");

Both also with a "/" prefix. But the file simply cannot be found.

Why is that? Might it be looking for the file in the root of A? Is it possible to find the file in module B when building A?

Thanks!

kutschkem :
new File("src/main/resources/foo.properties");

This is a path relative to the working directory. The working directory is wherever you called maven. So that's why it won't work when calling maven anywhere other than the directory of module B.

this.getClass().getClassLoader().getResourceAsStream("src/main/resources/foo.properties");

This won't work because the classpath is where maven put the classes, that is, target/classes.

What you need to do is add this file as resource in the maven build, then use the getResourceAsStream idea with the correct path. Since you used the standard maven layout, you probably don't need to anything and just use

this.getClass().getClassLoader().getResourceAsStream("foo.properties");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19906&siteId=1