20

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?

Jasper
  • 2,166
  • 4
  • 30
  • 50
udy
  • 199
  • 1
  • 1
  • 4

11 Answers11

20

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, or null if:

  • the resource could not be found, or
  • the invoker doesn't have adequate privileges to get the resource.

See also

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 2
    where should i put the properties file? – udy Jun 29 '10 at 09:53
  • Yes i checked that, so where should be the properties file? It is in same project right now. – udy Jun 29 '10 at 09:57
  • @udy: can you confirm first that `is` is `null` with a simple check/debugging session? – polygenelubricants Jun 29 '10 at 09:59
  • yes it is null, i have checked but not getting where to place the properties file. ? – udy Jun 29 '10 at 10:04
  • @udy: can you edit the question and add more information about what IDE you're using, where you currently put the properties file, and how you're running the project etc? – polygenelubricants Jun 29 '10 at 10:11
  • @udy: also, try `getClass().getResourceAsStream`, and/or adding `/` before the property name to make the location "absolute" (see http://lj4newbies.blogspot.com/2008/03/using-classgetresource-load-resource.html) – polygenelubricants Jun 29 '10 at 10:13
  • Ya i got it Thanks. Problem was that, i had manually copied the "properties" file in same package but it should have been outside the package but in same project.. – udy Jun 29 '10 at 10:20
9

Bugfixing is easier if you write more lines, like:

Properties properties = new Properties();
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
InputStream propertiesStream = contextClassLoader.getResourceAsStream("resource.properties");
if (propertiesStream != null) {
  properties.load(propertiesStream);
  // TODO close the stream
} else {
  // Properties file not found!
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • Oh, thanks, thanks, this works for me finally! I tried many of quite similar codes (for run within jar) before and I was already completely desperate. – Androdos Sep 17 '14 at 12:06
3

I had the same problem and was quite confused as I used it previously in a Sturts application. But the problem was that I didn't understand the type of ClassLoader that Struts returns is different than what Spring returns. And the way i figured it out was i printed out the object that was returned on to the system console like this:

System.out.println(Thread.currentThread().getContextClassLoader());

[
WebappClassLoader
context: /MyProject
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@1004901
]

It gave me the detail of the object, and in that I found its type to be of WebAppClassLoader which will start looking for files in the WEB-INF/classes/ folder after a build is done. So I went into the that folder and looked for where my file is located so I gave the path accordingly.

In my case it was located in /WEB-INF/classes/META-INF/spring/filename.extension

InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/spring/filename.extension");

Voilà!

That fixed it all.

Mark Lalor
  • 7,820
  • 18
  • 67
  • 106
mekbib.awoke
  • 1,094
  • 1
  • 9
  • 16
2

I had the same problem and I have resolved by doing the following

  1. File file = new File("resources.properties");
  2. System.out.println(file.getAbsolutePath());

and then put "resources.properties" file under that path.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
2

In Case its in eclipse clean the project and in case it is intellij rebuild the project it should start working

Jainender Chauhan
  • 749
  • 1
  • 4
  • 5
0

I had this problem with a third-party program and it turned out that I needed to include . in the classpath so that the program could read a local properties file in the current working directory.

Avi Flax
  • 50,872
  • 9
  • 47
  • 64
0

Many seem to have this problem and like me they give up after sometime. Here is what I had to get this working. The trick here to use relative path for file lookup is to make sure your classes folder contains resources files along with src files. Here is what I ended up doing.

1) If you are using eclipse make sure you proper .classpath setting present and do PROJECT CLEAN to see the resources files get generated under /classes. Notice the classpath-entries below for resource files place under src/main/resource

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry including="**/*.java" kind="src" output="target/test-classes" path="src/test/java"/>
    <classpathentry including="**/*.java" kind="src" path="src/main/java"/>
    <classpathentry kind="var" path="M2_REPO/javax/mail/mail/1.4.4/mail-1.4.4.jar"/>
    <classpathentry kind="var" path="M2_REPO/javax/activation/activation/1.1/activation-1.1.jar"/>
    <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="output" path="target/classes"/>
</classpath>

2) If you are using maven as well make sure you configure your pom.xml as per the https://maven.apache.org/guides/introduction/introduction-to-the-pom.html and do mvn clean install to see the files under target/classes

3) Once you have got the resource files under /classes the next thing to do in java is the following. Don't forget to have the forward slash.

try {
            properties.load(getClass().getResourceAsStream("/mail-config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

I could have added some images but did not have points. :)

josliber
  • 43,891
  • 12
  • 98
  • 133
Ajay Menon
  • 127
  • 6
0

Well it depends; As per javadoc ... The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application...

So if Thread.currentThread().getContextClassLoader() is in the main() function and you haven't created any thread then it should have the same package as that of the class containing method main. Otherwise it should be present in the class which has created the thread....

Favonius
  • 13,959
  • 3
  • 55
  • 95
0

Perhaps, I have plucked all my hairs out and going then I have found this solution out:

Properties dbParamProperties = new Properties();
         InputStream input = null;
        try {

            String pathOfAbsolute = this.getClass().getProtectionDomain().getCodeSource().getLocation().toString();
            String propertiesFilePath = pathOfAbsolute+"/properties/conf.properties";
            propertiesFilePath = propertiesFilePath.replace("file:/", "").replace("/", "\\");
           System.out.println(pathOfAbsolute);
           System.out.println(propertiesFilePath);
           Paths.get(new URI(pathOfAbsolute));
             input =  ClassLoader.getSystemResourceAsStream(propertiesFilePath);
           input = new FileInputStream(propertiesFilePath);
           dbParamProperties.load( input );
           dbUID =  dbParamProperties.getProperty("userName");
           dbURL =  dbParamProperties.getProperty("hosturl");
           dbPWD =  dbParamProperties.getProperty("password");
           dbPort = dbParamProperties.getProperty("port");
           dbSID =  dbParamProperties.getProperty("servicenameorsid");


        } catch (IOException e) {

            e.printStackTrace();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
Surajit Biswas
  • 779
  • 7
  • 25
0

I had the same problem and this helped me:

InputStream is;
try {

    is = this.getClass().getClassLoader().getResourceAsStream("config.properties");

    prop.load(is);

    String url = prop.getProperty("url");
    String user = prop.getProperty("user");
    String pass = prop.getProperty("password");
    is.close();
    // opening database connection to MySQL server
    con = DriverManager.getConnection(url, user, pass);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (SQLException e) {
    e.printStackTrace();
}
Community
  • 1
  • 1
-1

In my situatioan I get NullPointerException in this code

LogManager.getLogManager()
      .readConfiguration(MyClass.class.getResourceAsStream("config/logging.properties"));

I changed

LogManager.getLogManager().readConfiguration(AzLotteryTerm.class.getClassLoader().getResourceAsStream("config/logging.properties"));

and now works ok!

Black_Zerg
  • 87
  • 2
  • 3
  • 1
    Your first example didn't work because MyClass' package name will be automatically prepended to the resource path unless you make sure it starts with `/`. Look [here](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)) – dev Aug 31 '13 at 09:58