1

My main function uses set of hard coded parameters as given in the sample code. Objective: I want a cleaner code instead of hard coding these values inside main. Question: WIs there a way of defining all these parameters in a separate file like a configuration file and enabling access to main? Anybody who wants to change values will be required to modify only the parameter file. If there is a better way of handling the objective, please suggest so.

    public class Sample {

    public static void main(String[] arg) throws Exception {
    BufferedReader File = new BufferedReader(new FileReader("myfile.txt"));
            // parameter list
            String Parameter_1 = "Value_1";
            String Parameter_2 = "Value_2";
            .......
            //Function code
    }

3 Answers 3

6

Have a look at Java properties files; you can easily load (and save) them using the class java.util.Properties.

A properties file is a text file that contains key-value pairs, for example like this:

Parameter_1=Value_1
Parameter_2=Value_2

Loading a properties file is very easy:

Properties props = new Properties();
InputStream in = new FileInputStream("config.properties");
props.load(in);
in.close();

Then you can get the values:

String Parameter_1 = props.get("Parameter_1");
Sign up to request clarification or add additional context in comments.

1 Comment

+1, OP is trying to get rid of hardcoded values, so you could notice that the properties filename needn't be hardcoded either, he can use args[0]
1

Use Properties object:

Properties prop = new Properties();

        try {
               //load a properties file
            prop.load(new FileInputStream("config.properties"));

               //get the property value and print it out
                System.out.println(prop.getProperty("Value_1"));
            System.out.println(prop.getProperty("Value_2"));
            System.out.println(prop.getProperty("Value_3"));

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

Comments

0

The Preferences API is the preferred way, over Properties, at least as of Java 1.4. There's actually a comparison between other approaches and Preferences.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.