tags:

views:

104

answers:

6

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.

+5  A: 

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.

Jon Skeet
ok, thx. how would I load it as a file ? don't know how to use InputStream.
Attilah
configFile.load(new FileInputStream("DataTransfer/Config/DataTransfer.properties"));
Alberto Zaccagni
@Attilah: With the greatest of respect, if you don't know how to use `InputStream` you shouldn't be trying to write a J2EE application. Learn the core parts of Java first, and *then* move on to more complicated topics like J2EE.
Jon Skeet
+1  A: 

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.

Jan Jungnickel
Common issue? It's just a matter of understanding how it works.
BalusC
@BalusC indeed, but it's a commonly misunderstood mechanism.
Suppressingfire
@BalusC, yes, that's right. I just chose the wrong words.
Jan Jungnickel
A: 

I refer you to this question regarding best practices for reading configuration files in J2EE environments.

kgiannakakis
A: 

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(); }

valli
A: 

Use

configFile.load(new FileReader(new File(propertyFile)));

to check and load in same style

holub
A: 

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

Kennet