1. 程式人生 > >讀Properties檔案和往Properties檔案裡面寫內容

讀Properties檔案和往Properties檔案裡面寫內容

讀取配置檔案是一個很常用的操作;

讀檔案很簡單:

public static String getProperty(String key) {
		String value = "";
//第一步是取得一個Properties物件
		Properties props = new Properties();
//第二步是取得配置檔案的輸入流
		InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");//在非WEB環境下用這種方式比較方便
		try {
			InputStream input = new FileInputStream("config.properties");//在WEB環境下用這種方式比較方便,不過當配置檔案是放在非Classpath目錄下的時候也需要用這種方式
//第三步講配置檔案的輸入流load到Properties物件中,這樣在後面就可以直接取來用了
			props.load(input);
			value = props.getProperty(key);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}

往配置檔案裡面寫內容:

public static void setProperty(Map<String,String> data) {
//第一步也是取得一個Properties物件
		Properties props = new Properties();
//第二步也是取得該配置檔案的輸入流
//		InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			InputStream input = new FileInputStream("config.properties");
//第三步是把配置檔案的輸入流load到Properties物件中,
			props.load(input);
//接下來就可以隨便往配置檔案裡面新增內容了
//			props.setProperty(key, value);
			if (data != null) {
				Iterator<Entry<String,String>> iter = data.entrySet().iterator();
				while (iter.hasNext()) {
					Entry<String,String> entry = iter.next();
					props.setProperty(entry.getKey().toString(), entry.getValue().toString());
				}
			}
//在儲存配置檔案之前還需要取得該配置檔案的輸出流,切記,
如果該專案是需要匯出的且是一個非WEB專案,則該配置檔案應當放在根目錄下,否則會提示找不到配置檔案 OutputStream out = new FileOutputStream("config.properties"); //最後就是利用Properties物件儲存配置檔案的輸出流到檔案中; props.store(out, null); input.close(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }