I am using the following code to read a properties file:
Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().
getResourceAsStream("resources.properties");
pro.load(is);
And when I execute the code I'm getting the following error:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.getResource(RQMRestClient.java:66)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.main(RQMRestClient.java:50)
Why am I getting a NullPointerException
? And where should I save the resources.properties
file?
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.
It looks like ClassLoader.getResourceAsStream(String name)
returns null
, which then causes Properties.load
to throw NullPointerException
.
Here's an excerpt from documentation:
URL getResource(String name)
: Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.The name of a resource is a
'/'
-separated path name that identifies the resource.Returns: A
URL
object for reading the resource, ornull
if:
- the resource could not be found, or
- the invoker doesn't have adequate privileges to get the resource.
getResource
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With