views:

95

answers:

5

I am trying to load properties from a file (test.properties)

The code I use is as follows:

URL url = getClass().getResource("../resources/test.properties");
properties.load(url.openStream());

But when executing the second line I get a NPE. (null pointer exception)

I'm not sure what's wrong here... I have checked that the file exists at the location where URL points to...

Any help is appreciated....

+2  A: 

I could be wrong, but I don't believe you can use ".." like that in a call to getResource(). I suggest you try an "absolute" resource:

URL url = getClass().getResource("/path/to/resources/test.properties");
Jon Skeet
A: 

getClass().getResource() resolves the resource relative to the given class. Try getClass().getClassLoader().getResource().

lexicore
+2  A: 

The javadoc for Class.getResource(String) says:

Returns: a URL object or null if no resource with this name is found

Most likely, the problem is that getResource is not finding the resource it is looking for. I am very suspicious of the use of ".." in the resource name. The javadoc does not say that getResource treats "." or ".." path components as having special meaning.

It is also possible that properties is null ...

Stephen C
+1  A: 

Is it perhaps the properties object that is null?

Michael Borgwardt
This was the problem.. I just forgot to instantiate the properties object... And was so confident that there was something wrong with the loading of the file... Thanks for help...
markovuksanovic
@markovuksanovic: you're welcome... we've all wasted time looking for a complex solution to a simple problem one time or another.
Michael Borgwardt
+1  A: 

The answer to whether or not getResource will find your file depends on your system classloader. The classloader is called, but before the classloader is called, the following transformation is made on the string you pass in.

From the Class javadoc:

  • 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

    Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

So, the question becomes: will the classloader you are using be able to resolve modified_package_name/../resources/test.properties?

justkt