Chan Chen Coding...

          Java Properties file examples

          In Java, properties file is always used to store the configuration data or settings. In this example we will show you how to read and write to/from a properties file.

          1. Example 1

          In this example, set the property value and write it into a properties file named “config.properties“. The new saved properties file will be stored at your project root folder.

          package com.mkyong.common;   
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.util.Properties;  
          public class App {
              public static void main( String[] args )
              {
                  Properties prop = new Properties();
            try {
          //set the properties value
          prop.setProperty("database", "localhost");
          prop.setProperty("dbuser", "mkyong");
          prop.setProperty("dbpassword", "password");
            //save properties to project root folder
          prop.store(new FileOutputStream("config.properties"), null);
            } catch (IOException ex) {
          ex.printStackTrace();
          }
          }
          }

          Output – The content of the file “config.properties

          #Mon Jan 11 18:54:40 MYT 2010 
          dbpassword=password
          database=localhost
          dbuser=mkyong

          2. Example 2

          In this 2nd example, load a properties file named “config.properties” and retrieved the saved property value.

          package com.mkyong.common;   
          import java.io.FileInputStream;
          import java.io.IOException;
          import java.util.Properties;
            public class App {
          public static void main( String[] args )
          {
          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("database"));
          System.out.println(prop.getProperty("dbuser"));
          System.out.println(prop.getProperty("dbpassword"));
            } catch (IOException ex) {
          ex.printStackTrace();
          }
            }
          }

          Output

          localhost
          mkyong
          password


          -----------------------------------------------------
          Silence, the way to avoid many problems;
          Smile, the way to solve many problems;

          posted on 2012-06-07 13:05 Chan Chen 閱讀(363) 評論(0)  編輯  收藏 所屬分類: Scala / Java

          主站蜘蛛池模板: 广灵县| 芒康县| 佛山市| 湘乡市| 大竹县| 钦州市| 永年县| 太和县| 石河子市| 界首市| 大悟县| 册亨县| 连南| 堆龙德庆县| 峡江县| 许昌市| 潢川县| 宁海县| 和顺县| 曲靖市| 大新县| 马关县| 闸北区| 灵寿县| 临澧县| 稷山县| 纳雍县| 永清县| 咸宁市| 阿瓦提县| 龙口市| 楚雄市| 东乡| 海阳市| 双牌县| 谢通门县| 成安县| 保靖县| 浦县| 确山县| 腾冲县|