java 操作Properties文件

Properties文件也就是属性文件,用来存放一些属性供程序读取。

这些属性由“=”左边的key和“=”右边的value构成,基本结构如下:

key=value

下面给出一个非常简单的Properties文件:

#Fri Jul 13 14:26:52 CST 2012
username=Jack password=123456 age=18 address=beijing

那么我们该如何操作.properties文件呢?在Java.util包下面有一个类叫Properties,提供了一些方法供我们使用。

Properties()构建一个无默认值的空属性列表

void load(InputStream in) 从指定的输入流中读取属性列表(键和元素对)

String getProperty(String key)用指定的键在此属性列表中搜索属性

Object setProperty(String key,String value) 将指定的key映射到指定的value

void store(OutputStream out,String comments)将Properties表中的属性列表写入输出流

好了,下面给出个简单的程序看看如何操作.properties文件

首先,根据指定的key值读取对应的value

public static String readValue(String filePath, String key) {
        Properties props = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            props.load(in);
            String value = props.getProperty(key);
            System.out.println(key + "=" + value);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

另一种方法:

import java.util.Locale;
import java.util.ResourceBundle;

public class ReadValue {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ResourceBundle rb=ResourceBundle.getBundle("app", Locale.CHINA);
        System.out.println(rb.getString("keyname"));
    }

}

 

读取全部的属性信息

public static void readProperties(String filePath) {
        Properties props = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(
                    filePath));
            props.load(in);
            Enumeration<?> en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String Property = props.getProperty(key);
                System.out.println(key + "=" + Property);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

向.properties文件中写入信息

public static void writeProperties(String filePath, String parameterName,
            String parameterValue) {
        Properties prop = new Properties();
        try {
            InputStream fis = new FileInputStream(filePath);
            prop.load(fis);
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(parameterName, parameterValue);
            prop.store(fos, "Update '" + parameterName + "' value");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

其中

prop.store(fos, "Update '" + parameterName + "' value");这句代码会在文件头添加一句描述信息:
#Update 'address' value
#Fri Jul 13 15:02:27 CST 2012
address=hainan
age=18
password=123456
username=Jack

 

OK,本文到此结束,欢迎提出宝贵意见。
posted @ 2012-07-13 15:05  一瓶珍情  阅读(3849)  评论(0编辑  收藏  举报