There is a maven project A. Once I do mvn clean install, the project builds and the jar is available at my local repository ie c:\\repository\\com\\stackoverflow\\A\\A.jar<
If the A class (that is bundled in your A.jar) wants to load the xml from the jar and it tries to access it in the way shown in your first code example then it does not access p.xml
inside your jar. It accesses the file at that location.
It is easy to test if this is your case. After your jar is created, temporarily delete p.xml
from the file system and run A class. It will fail to load it.
When a class needs to load a resource that is bundled in a jar then it does not use File
but the classloader.
From the names you provide, I assume that your class A is in package: com.stackoverflow.A
The xml file is in the package com.stackoverflow.A.res
All the approaches below will load a stream with your xml
InputStream is = null;
// Using class - relative to the class location because path does not start with "/"
is = SimpleWriter.class.getResourceAsStream("res/p.xml");
// Using class - absolute path because path starts with "/"
is = SimpleWriter.class.getResourceAsStream("/com/stackoverflow/A/res/p.xml");
// Using classloader - path is *always* absolute. Note that leading "/" is missing
is = SimpleWriter.class.getClassLoader().getResourceAsStream("com/stackoverflow/A/res/p.xml");
I think you're asking the wrong question. You probably want to know has to access p.xml
. The best way is to put A.jar on the classpath, which you do by specifying it as a dependency in the pom.xml of "the other Maven Project".
In your code you do the following:
Foo.class.getResource("/thePackagePath/to/p.xml");
By trying to access the xml as a file, you make your project very bad portable to other systems.