首页 > 代码库 > 5分钟教你学会Java properties

5分钟教你学会Java properties

以前年轻的时候,总喜欢在代码中把参数的值写死,改一遍跑一遍,可移植性太糟糕了。自从用了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