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

          主站蜘蛛池模板: 奇台县| 中江县| 奈曼旗| 伊金霍洛旗| 郴州市| 达拉特旗| 大渡口区| 桂林市| 石柱| 伊金霍洛旗| 泸溪县| 靖西县| 赫章县| 扶绥县| 罗平县| 左贡县| 大关县| 荥经县| 石屏县| 桂林市| 池州市| 南乐县| 扬中市| 伊通| 乐至县| 昔阳县| 筠连县| 灌南县| 绥阳县| 延寿县| 绥江县| 恭城| 哈尔滨市| 杭锦后旗| 上饶县| 蓬安县| 红原县| 黄龙县| 丁青县| 扎囊县| 云南省|