Reputation: 17930
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.
Upvotes: 0
Views: 4249
Reputation: 2114
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.
Upvotes: 1
Reputation: 818
Use
configFile.load(new FileReader(new File(propertyFile)));
to check and load in same style
Upvotes: 0
Reputation: 5796
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
Upvotes: 0
Reputation: 5931
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(); }
Upvotes: 0
Reputation: 104178
I refer you to this question regarding best practices for reading configuration files in J2EE environments.
Upvotes: 0
Reputation: 1500535
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.
Upvotes: 5