1. 程式人生 > >Java中的properties檔案的讀取

Java中的properties檔案的讀取

專案中難免會用到一些業務相關的變數,有時可能需要根據專案的不同而去修改它的值,所以為了方便性以及可變性,這些需要寫到一個配置檔案中,

常用的有寫在xml中,當然也有寫成properties檔案中的,本篇就是介紹如何讀取properties中的值的。

這個properties中的特點和Map有點像,通過key=value的方式儲存。

1、如果沒有等號,則value為空

2、如果有多個等號,第一個等號之前的為key

3、如果以等號開始,就是key為空,value為等號後面的值了。

4、正常情況就是一個等號,並且等號前後都有值。

下面就是讀取properties的程式碼,很簡單的,其實就是讀取檔案了。

package com.jay.test.proeprties;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class PropertiesUtil {

	public static void main(String[] args) {
		readFromProperties("db.properties");
	}

	/**
	 * 從properties檔案中讀取資料
	 * 
	 * @param filePath
	 */
	public static Properties readFromProperties(String filePath) {
		InputStream in = PropertiesUtil.class.getResourceAsStream(filePath);
		Properties properties = new Properties();
		try {
			properties.load(in);
			Enumeration<?> enumeration = properties.propertyNames();
			while (enumeration.hasMoreElements()) {
				String keyString = (String) enumeration.nextElement();
				String valueString = (String) properties.getProperty(keyString);
				System.out.println("key:      " + keyString + "   value: " + valueString);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	return properties;
	}
/**更新 value值或增加key--value
**/
 public static Properties updateProperties(Map<String, String> keyValueString, String fileName) {
        Properties properties = readFromProperties(fileName);
        if (properties == null || keyValueString == null) {
            return null;
        }
        try {
            String pathString = PropertiesReaders.class.getClassLoader().getResource(fileName).getPath().toString();
            //修改了目錄中有空格轉義為%20的原因。
            URI uri = new URI(pathString);
            OutputStream outputStream = new FileOutputStream(uri.getPath());
            for(Iterator<Entry<String, String>> iterator=keyValueString.entrySet().iterator();iterator.hasNext();){
                Entry<String, String> entry = iterator.next();
                properties.put(entry.getKey(), entry.getValue());
            }          //修改多個key值時,需要最後才store下。否則會出問題的
            properties.store(outputStream, "update linkproperties ");
            outputStream.close();
        } catch (FileNotFoundException e) {
            properties = null;
        } catch (IOException e) {
            properties = null;
        } catch (URISyntaxException e) {
            properties = null;
        }
        return properties;
    }

db.properties配置檔案中的內容是

name=boy
value=eleven=
placechinese
=1344
name=girl

執行完程式碼後的效果如下所示:發現key相同後,後面的會覆蓋之前的,這個就是和map特別像了。

key:      name   value: girl
key:      placechinese   value: 
key:      value   value: eleven=
key:         value: 1344

看了原始碼之後,會發現Properties這個類繼承了Hashtable,而去load檔案流時,使用的是Hashtable的put方法,

所以為什麼和map像這就不用多說了。