Monday

Read a .properties file inside the class folder

package read.properties.file;

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

public class App {

       public static void main(String[] args) {
              App app = new App();
              app.readProperties();
       }

       //read a .properties file inside  the class folder
       private void readProperties() {

              Properties prop = new Properties();
              InputStream inputStream = null;
              String filename = "config.properties";

              try {
                     inputStream = getClass().getClassLoader().getResourceAsStream(filename);
                     if (inputStream == null) {
                           System.out.println("Unable to find " + filename);
                           return;
                     }

                     prop.load(inputStream);

                     // get all values
                     Enumeration<?> e = prop.propertyNames();
                     while (e.hasMoreElements()) {
                           String key = (String) e.nextElement();
                           String value = prop.getProperty(key);
                           System.out.println("Key : " + key + ", Value : " + value);
                     }

                     // get only one value you wanted
                     System.out.println("get only one value you wanted: user: " + prop.getProperty("user"));

              } catch (Exception e) {
                     // throw or log the exception

              } finally {
                     if (inputStream != null) {
                           try {
                                  inputStream.close();
                           } catch (IOException e) {
                                  // throw or log the exception
                           }
                     }
              }

       }

}

Config.properties

user=eda
password=less talk more code
outputs:
Key : user, Value : eda
Key : password, Value : less talk more code
get only one value you wanted: user: eda


No comments:

Post a Comment