1

In my package com.foo.bar, I have two files, Config.java and config.properties. At the top of Config, I'm trying to read config.properties and set some internal variables:

public class Config
{
    public static String foo;
    public static String bar;
    static
    {
        try
        {
            System.out.println("Loading");
            InputStream is =     Config.class.getClassLoader().getResourceAsStream("config.properties");
            System.out.println("stream: " +  is );

            Properties props = new Properties();
            props.load(is);

            foo = props.getProperty("foo");
            bar = props.getProperty("bar");

            is.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    //snip...
}

Despite config.properties file existing in the same package, I get this output:

Loading
stream: null

And then a NullPointerException on the line props.load(is).

What am I doing wrong? From some googling, it seems that I'm using the correct method for reading the file. Is it because I'm doing this in a static block, that I'm having this issue?

ngrashia
  • 9,869
  • 5
  • 43
  • 58
Ali
  • 261,656
  • 265
  • 575
  • 769

2 Answers2

2

Try replacing this line

InputStream is =     Config.class.getClassLoader().getResourceAsStream("config.properties");

With this

InputStream is =  Config.class.getResourceAsStream("config.properties");

I hope it works :)

vkg
  • 1,839
  • 14
  • 15
  • @vkg You were on the right track the first time. Adding getClass() was definitely wrong though. I suspect the file isn't where he thinks it is. – user207421 May 12 '14 at 03:18
  • 1
    I just tested it and it works. I tested it exactly in a static block as you have. The answer is now what I originally posted. – vkg May 12 '14 at 03:19
  • @ClickUpvote It works as long as the file is in the right place. Clearly it isn't in your case. – user207421 May 12 '14 at 03:21
2

Replace this:

InputStream is =     Config.class.getClassLoader().getResourceAsStream("config.properties");

With this:

InputStream is =  Config.class.getResourceAsStream("config.properties");

This assumes that the Config .class file and the .properties are in the same directory at runtime of course, i.e. that the .properties file has been deployed. Having it in the same directory as the source file isn't necessarily a guarantee of that.

user207421
  • 305,947
  • 44
  • 307
  • 483