[java] Reading Properties file in Java

I have the following code trying to read a properties file:

Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);

I get an exception at the last line. Specifically:

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 Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)

thanks, Nikos

This question is related to java properties

The answer is


Based on your exception, the InputStream is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:

InputStream stream = loader.getResourceAsStream("/myProp.properties");

Specify the path starting from src as below:

src/main/resources/myprop.proper

You can use java.io.InputStream to read the file as shown below:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(myProps.properties); 

if your config.properties is not in src/main/resource directory and it is in root directory of the project then you need to do somethinglike below :-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

I see that the question is an old one. If anyone stumbles upon this in the future, I think this is one simple way of doing it. Keep the properties file in your project folder.

        FileReader reader = new FileReader("Config.properties");

        Properties prop = new Properties();
        prop.load(reader);

Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }

Note the instantiating of the file input stream in try-with-resources block. Since a FileInputStream is autocloseable, it will be automatically closed after the try-with-resources block is exited. If you want to use a simple try block, you must explicitly close it using fis.close(); in the finally block.


Make sure that the file name is correct and that the file is actually in the class path. getResourceAsStream() will return null if this is not the case which causes the last line to throw the exception.

If myProp.properties is in the root directory of your project, use /myProp.properties instead.


Given the context loader.getResourceAsStream("myPackage/myProp.properties") should be used.

Leading '/' doesn't work with ClassLoader.getResourceAsStream(String) method.

Alternatively you could use Class.getResourceAsStream(String) method, which uses '/' to determine if the path is absolute or relative to the class location.

Examples:

myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")

Properties prop = new Properties();

try {
    prop.load(new FileInputStream("conf/filename.properties"));
} catch (IOException e) {
    e.printStackTrace();
}

conf/filename.properties base on project root dir


You can't use this keyword like -

props.load(this.getClass().getResourceAsStream("myProps.properties"));

in a static context.

The best thing would be to get hold of application context like -

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/app-context.xml");

then you can load the resource file from the classpath -

//load a properties file from class path, inside static method
        prop.load(context.getClassLoader().getResourceAsStream("config.properties"));

This will work for both static and non static context and the best part is this properties file can be in any package/folder included in the application's classpath.


For Reading Properties file with its original order:

    File file = new File("../config/edc.properties");
    PropertiesConfiguration config = new PropertiesConfiguration();
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    layout.load(new InputStreamReader(new FileInputStream(file)));

    for(Object propKey : layout.getKeys()){
        PropertiesConfiguration propval =  layout.getConfiguration();
        String value = propval.getProperty((String) propKey).toString();
        out.print("Current Key:" + propkey + "Current Value:" + propval + "<br>");
    }

If your properties file path and your java class path are same then you should this.

For example:

src/myPackage/MyClass.java

src/myPackage/MyFile.properties

Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);

You can use ResourceBundle class to read the properties file.

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");

None of the current answers show the InputStream being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream() returning null when the resource is not found (this will lead to a NullPointerException with the confusing message, "inStream parameter is null"). You need something like the following:

String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

Your file should be available as com/example/foo/myProps.properties in classpath. Then load it as:

props.load(this.getClass().getResourceAsStream("myProps.properties"));


You can find information on this page:
http://www.mkyong.com/java/java-properties-file-examples/

Properties prop = new Properties();
try {
    //load a properties file from class path, inside static method
    prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));

    //get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} 
catch (IOException ex) {
    ex.printStackTrace();
}