3

Using this bit of code to try and set a policy file:

ClassLoader cl= getClass().getClassLoader();
URL policyURL =cl.getResource("res/policy/new_policy.policy");
System.setProperty("java.security.policy", policyURL.toString());

And I get a java.lang.NullPointerException on the last line. The file is in my project directory in the correct path.

Question: What could cause this exception?

Answer: Running from eclipse, the path was constructed relative to the main project folder, not the project's bin folder. Considering that, moving the res folder in the bin folder solved the issue without changing any of the code above.

CosminO
  • 5,018
  • 6
  • 28
  • 50

2 Answers2

1

If the path is in you project, add a /

cl.getResource("/res/policy/new_policy.policy")

But I would suggest you print the value of policyURL to check that you retrieve the file ok.

If you are executing in Eclipse, remember that the resources must be in a resources folder so they go to classes folder when build.

Eclipse only execute classes, and the classes live in output folder (bin).

ssedano
  • 8,322
  • 9
  • 60
  • 98
  • tried it like that, the same result. On printing the URL, it is null. So why does it not load the resource? – CosminO Sep 18 '12 at 13:36
  • 1
    are you executing a jar? from which folder? are you expanding the jar? Are you executing it from eclipse? – ssedano Sep 18 '12 at 13:38
  • 1
    the new_policy is in the bin or target (where the classes are outputted)? – ssedano Sep 18 '12 at 14:23
  • works now! I used to put everything I used (images and other files I'm using for an app) in the main project folder and it worked. Should I note that anything used with getResource() should be in bin (or the path used should be relative to that of bin)? – CosminO Sep 18 '12 at 14:33
1

This would happen if:

policyURL.toString()

is null, as the property values are stored in a Hashtable and the the Hashtable class checks whether the value is null in it's put method and throws a NullPointerException if it is. I would make sure that your policyUrl Object is being constructed correctly.

Chris B
  • 925
  • 4
  • 14