2

i have a maven module BaseProject with java classes in src/main/java. Some classes are loading xml-files from the src/main/resource folder. That works pretty nice.

I have a second maven project TestProject that has uses the BaseProject as dependency. TestProject is my JUnit test project, so there are classes only in src/test/java.

If I use some of the classes from the BaseProject that load any resource I get a null because the resource file can not be found.

I assume that the src/main/resource folder from my TestProject is considered in this situation as the place to look for the resource files.

So how do i load the resource files in the BaseProject in a way that it will look always in its own src/main/resource folder?

And here is how i do it at the moment:

 InputStream inputStream = MyBaseClass.class
            .getResourceAsStream(
            "foo/bar/hello.xml" );
 String content = new Scanner( inputStream, "UTF-8" ).useDelimiter( "\\Z" ).next();
elect
  • 6,765
  • 10
  • 53
  • 119
martin
  • 980
  • 1
  • 13
  • 28
  • It should work. Make sure the jar of the main project (installed in your .m2 local repository) contains the XML file. – JB Nizet Oct 18 '11 at 09:09

1 Answers1

1

getResourceAsStream("path") looks up the resource relatively from the current class. If foo.bar is a full package name, you should use absolute path getResourceAsStream("/foo/bar/hello.xml")

kan
  • 28,279
  • 7
  • 71
  • 101
  • Doh, layer 8 problem. Missed the maven resource plugin. Now it works. Thanks a lot – martin Oct 18 '11 at 09:48
  • Is there anyway you could list the files under a directory? For example, something like MyClass.class.getResourceAsStream("/foo/bar").list() ? – nemo Nov 24 '15 at 00:25
  • @VijayRatnagiri I hope you are actually mean resources, not just files. Just google it, e.g. http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – kan Nov 24 '15 at 15:21