码迷,mamicode.com
首页 > 编程语言 > 详细

5分钟教你学会Java properties

时间:2015-01-07 22:06:35      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

以前年轻的时候,总喜欢在代码中把参数的值写死,改一遍跑一遍,可移植性太糟糕了。自从用了Properties类之后,省事了,代码也规范了一点了。
也就是将常用的,且经常需要修改的参数放置在xx.properties文件中,利用Java中提供的Properties类读取文件中的参数值,从而避免多次在代码中修改参数的值,一劳永逸。

Properties其实是继承自HashTable,所以用起来也很简单,提供的操作主要有:

load(inputStream) : 加载配置文件
store(outputStream,comment):将新生成的Properties对象写出到文件中去,comment是添加说明性的文字;
getProperty(name):获取某个属性的值;
setProperty(name,value):设置某个属性的值;这个属性可以事先不存在
putProperty(name,value):新增一个属性值

  

package PropertiesTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author wangjj
 *
 *         Jan 7, 2015
 */
public class TestPropertiesClass {

     public static Properties properties;

     public TestPropertiesClass(String propertiesFile) throws Exception {

           properties = new Properties();

           // properties文件的格式是: #comment,argument=value
          FileInputStream input = new FileInputStream(new File(propertiesFile));

           // 从input stream中读取数据
           properties.load(input);
     }

     /**
      * 测试properties中提供的方法:get,set,store,put
      *
      * @throws IOException
      * @throws FileNotFoundException
      */
     public void run(String outputProperty) throws FileNotFoundException,
              IOException {

           // read properties
          String firstname = properties.getProperty("firstname" );
          String hobby = properties.getProperty("hobby" );
          System. out.println("firstName: " + firstname);
          System. out.println("hobby:" + hobby);

           // set existed property
           properties.setProperty("firstname" , "jing" );
          firstname = properties.getProperty("firstname" );
          System. out.println("changed firstName:" + firstname);

           // set non-existed property
           properties.setProperty("hello" , "world" );
          System. out.println("hello :" + properties.getProperty("hello" ));

           // put non-existed property
           properties.put("newProperty" , "newValue" );
          System. out.println("New property :"
                   + properties.getProperty("newProperty" ));

           properties.store(new FileOutputStream(new File(outputProperty)),
                    "outputProperty");
     }

     public static void main(String[] args) throws Exception {
          String properFile = "conf/test.properties";
          TestPropertiesClass testProperties = new TestPropertiesClass(properFile);
          String outputProperty = "conf/testNew.properties" ;
          testProperties.run(outputProperty);
     }
}

  

5分钟教你学会Java properties

标签:

原文地址:http://www.cnblogs.com/jing77jing/p/4209447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!