learner
learner

Reputation: 1982

Passing java property via a property file

I pass bunch of properties to my java command using -D. But I was wondering is there a way to keep these properties in a file and pass that file without making any code change.

Is this possible?

Upvotes: 2

Views: 7228

Answers (3)

Ofer Lando
Ofer Lando

Reputation: 824

As far as I know there's no "-D" equivalent to provide a properties file, but you can pass the file name as a parameter and read it in your code. It won't work "without making any code change", but it's a rather simple change:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropReader {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String strPropertiesFile = args[0];

        Properties props = new Properties();
        InputStream is = PropReader.class.getResourceAsStream(strPropertiesFile);
        try {
            props.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(Object key : props.keySet())
        {
            System.out.println(props.getProperty((String)key));
        }
    }
}

Upvotes: 0

Sergio
Sergio

Reputation: 199

You can use -D to point to a properties file. Then, you can create a FileReader from the file, instantiate a properties object and use the load method of the properties object to populate from the reader. Is it a standlaone application or a web application? In the second case you can use getResourceAsStream instead of creating a FileReader.

    String fileName = System.getProperty("fileName");

    Properties props = new Properties();
    try (Reader reader = new FileReader(fileName)) {
        props.load(reader);
    }

Upvotes: 2

roeygol
roeygol

Reputation: 5028

You need to get the String[] args which you're getting in the main function and put it to .properties file.

Then, also upload the properties file into a map and then read the values you need without reading the file over and over again. In this way, you will have both values in the file and a map each time the program is starting.

Example:

public SomeClass{

private static HashMap<String, String> propertiesMap = HashMap<String, String>();

public static void main(String[] args) {
     //args are your parameters that you're getting from cmd operation
     createPropertiesFile(args);

}

private static void createPropertiesFile (String[] args) {
//here you will create the file with properties and also the map above
}

public static getProperty(String prop){
     return map.get(prop)==null ? null : map.get(prop);
}
}

Usage in some other class

SomeClass.getProperty("<some property you got>");

In some other way, the parameter you're passing to main function can either be a path to your properties file.

Upvotes: 0

Related Questions