Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a properties file in Java and eclipse

Tags:

java

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.

like image 515
star1 Avatar asked May 03 '15 06:05

star1


People also ask

How do I create a properties file?

Create a properties fileRight-click and select Add New Properties File. A new properties file will be added to your project. The new file will be selected and highlighted in the list. Type a name for your properties file, for example, "Properties".

What is a properties file in Java?

properties is a file extension for files mainly used in Java-related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.


1 Answers

  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

like image 127
mirmdasif Avatar answered Oct 03 '22 23:10

mirmdasif