java 修改 properties

來源:互聯網
上載者:User

使用java 處理 properties 熟悉檔案是一件非常簡單的事情。先貼上幾句別人說的話先:

Properties類的重要方法
Properties 類存在於胞 Java.util 中,該類繼承自 Hashtable
1. getProperty ( String  key) ,   用指定的鍵在此屬性列表中搜尋屬性。也就是通過參數 key ,得到 key 所對應的 value。
2. load ( InputStream  inStream) ,從輸入資料流中讀取屬性列表(鍵和元素對)。通過對指定的檔案進行裝載來擷取該檔案中的所有鍵 - 值對。以供 getProperty ( String  key) 來搜尋。
3. setProperty ( String  key, String  value) ,調用 Hashtable 的方法 put 。他通過調用基類的put方法來設定 鍵 - 值對。

4. store ( OutputStream  out, String  comments) ,以適合使用 load 方法載入到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出資料流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的檔案中去。
5. clear () ,清除所有裝載的 鍵 - 值對。該方法在基類中提供。

 

package chenluozhi;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Enumeration;import java.util.HashMap;import java.util.Map;import java.util.Properties;/** * properties 文檔解析測試 * @author 陳羅志 * @date 2011-10-25 * @config.properties 放在 src/bin 目錄下 */public class PropertiesTest {public static Map actionMap = new HashMap(); public PropertiesTest() {}public void operateProperties() {Properties prop = new Properties();try {prop.load(this.getClass().getResourceAsStream("/config.properties"));System.out.println("根據key(login)隨意找出一個對應的值:"+prop.getProperty("login"));Enumeration<Object> e = prop.keys();//枚舉所有 key-value對while (e.hasMoreElements()) {String key = (String) e.nextElement();System.out.println(key + "=" + prop.getProperty(key));//根據這一思想,我們可以把對應的類全部載入到 記憶體,使用 hashmap存放,哈哈。太強大了。//String className = prop.getProperty(key);//System.out.println("正載入:"+className);//Class c = Class.forName(className);//actionMap.put(key, c.newInstance());}OutputStream fos = new FileOutputStream(this.getClass().getResource("/config.properties").getPath());//修改一個prop.setProperty("modify", "modify-by meme");//添加一個prop.setProperty("add", "add-by me");prop.store(fos,"this is header");fos.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}public static void main(String args[]) {PropertiesTest p = new PropertiesTest();p.operateProperties();}}

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.