star1
star1

Reputation: 217

Creating a properties file in Java and eclipse

I want to create a config.properties file, in which I want to store all the key and values instead of hard coding them in the Java code.

However, I do not know how to create a properties file in eclipse. I researched and found help on how to read a properties file. I need help with how to create it.

Here are my specific questions:

  1. Can a config.properties file be created in eclipse, and data be typed directly into it as though the config.properties is similar to text editor?
  2. If it can be directly created, the can you please let me know the steps to create this properties file?
  3. I am assuming that properties file can be created just like how java project, java class etc are created (by right clicking at package or project level). Is this correct assumption?
  4. Or creating a properties file and adding data to it needs to be done by java coding?

I will greatly appreciate any help.

Upvotes: 19

Views: 81675

Answers (1)

mirmdasif
mirmdasif

Reputation: 6354

  1. Create a new file from file menu Or press Ctrl+N
  2. In place of file name write config.properties then click finish

Then you can add properties your property file like this

dbpassword=password
database=localhost
dbuser=user

Example of loading properties

public class App {
  public static void main(String[] args) {

    Properties prop = new Properties();
    InputStream input = null;

    try {

        input = new FileInputStream("config.properties");

        // load a properties file
        prop.load(input);

        // 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();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

  }
}

By Edit

By Edit

Upvotes: 20

Related Questions