I'm having some trouble finding a config file with classpath.
I use :
InputStream stream = myclass.class.getResourceAsStream("properties.file");
The properties.file is located under config directory.
When running the program with eclipse, it works.
I just added config folder in the classpath in the launch configuration.
But If I want to run the exported jar like this :
java -jar -cp C:\project\lib;C:\project\config myclass.jar
I get the oh wonderful java.lang.NullPointerException because it can't find the file.
This sounds classic and stupid but I can't find a clue.
What does eclipse do that I don't ?
Thanks
解决方案
You should use absolute path for class (If you don not want to put the properties file in your jar relative to the class)
InputStream stream = myclass.class.getResourceAsStream("/properties.file");
or simply
InputStream stream = myclass.class.getClassLoader().getResourceAsStream("properties.file");
And then ensure that the path to the dir containing this resource file is specified in the classpath when you run the jar so that the systemclassloader will be able to find this resource.