java 操作Properties文件

来源:互联网 发布:淘宝客领取优惠券 编辑:程序博客网 时间:2024/05/21 07:54

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

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

key=value

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

#Fri Jul 13 14:26:52 CST 2012
username=Jackpassword=123456age=18address=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 2012address=hainanage=18password=123456username=Jack

 

OK,本文到此结束,欢迎提出宝贵意见。
0 0
原创粉丝点击