I have a method :
private String getProperty(String property) throws IOException,ConfigException {
// first test if the config file exists.
String propertyFile = "DataTransfer/Config/DataTransfer.properties"开发者_开发问答;
if(!new File(propertyFile).exists()) {
throw new ConfigException("the config file doesn't exist." +
" Make sure the file : \""+propertyFile+"\" exists.");
}
// retrieve the property
Properties configFile = new Properties();
configFile.load(this.getClass().getClassLoader()
.getResourceAsStream(propertyFile));
String prop = configFile.getProperty(property);
return prop;
}
Unfortunately, I keep getting a java.lang.NullPointerException
at the ConfigFile.load()
level.
I checked my variables in debug mode, none of them is null.
I don't know what's the cause for this exception.
You've checked that it exists as a file in the current working directory. You haven't checked that it exists on the classpath.
If you know it exists as a file, why not load it as a file?
If you want to load it from the classpath, why not change the check to make sure it exists on the classpath?
Basically you need to be consistent between your checking and your loading.
ClassLoader#getResourceAsStream(String) returns null
if the resource cannot be found by the ClassLoader hierarchy. This will most likely be the root cause.
Classloading, especially in J2EE-Environments, is often misunterstood.
Use
configFile.load(new FileReader(new File(propertyFile)));
to check and load in same style
I refer you to this question regarding best practices for reading configuration files in J2EE environments.
You can try like this FileInputStream infile = new FileInputStream(new File(libjavaFolder+"log4j.properties")); if(infile != null) { Properties logProps = new Properties(); logProps.load(infile); infile.close(); }
Make sure that the configfile is in that particular folder and that you're actually looking in the right path. I usually add something like this before the load method:
System.out.println(this.getClass().getClassLoader().getResource(".").getFile());
This will print the absloute path
精彩评论