can I load resource from classpath if set to any directory?
I want to load a resource with this:
InputStream iStream = Config.class.getResourceAsStream("autopublisherpath.cfg");
So I set the CLASSPATH to make it work. This is my dir hierarchy:
- autopublisher
.classes
.lib
.resources
If I add %AUTOPUBLISHER_HOME%\resources\config to my classpath I cannot get the resource. Otherwise if I put my .cfg file in classes and add %AUTOPUBLISHER_HOME%\classes the resource is loaded properly. The classes dir doesn't conta开发者_如何学Pythonin anything other than the autopublisherpath.cfg.
Ultimately I want to call:
java com.test.Something
Where something is loading the resource. The thing is I want user to modify this config file so I do not include it inside my jar packaging.
Am I not understanding the CLASSPATH correctly?
thank you
One thing to pay attention to when using getResourceAsStream
is the format of the resource name that you are retrieving. By default if you do not specify a path, e.g., "autopublisherpath.cfg", the classloader will expect that the resource being specified is within the same package as the Class on which you executed the getResourcesAsStream
method. The reason for this behavior can be found in the JVM documentation for getResourceAsStream:
- If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
- Otherwise, the absolute name is of the following form:
modified_package_name/name
In your particular example, if the Config
class was located in the com.test.config package, then the resource name of "autopublisherpath.cfg" would be converted to "/com/test/config/autopublisherpath.cfg" (period in package is replaced with a '/' character). As a result, keeping with your original project hierarchy, you would need to place the file into the location:
autopublisher/resources/config/com/test/config
where autopublisher/resources/config
was added as part of application's execution classpath.
If you are looking to add a specific config directory to your classpath and want the file to be located in the root of that directory, then you need to prefix the name of the file with a '/' character, which specifies that the resource should be in the root package of the classpath.
InputStream iStream = Config.class.getResourceAsStream("/autopublisherpath.cfg");
Using this code, you should be able to add the resource/config
directory to your classpath and read the file as expected.
On a side note, the getResourceAsStream
method loads the resource using the Classloader of the class from which it was executed (in this case Config). Unless your application uses multiple class loaders, you can perform the same function from any of your class instances using this.getClass().getResourceAsStream(...)
.
精彩评论