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,本文到此結束,歡迎提出寶貴意見。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM