java properties增刪改查
java properties增刪改查public static void main(String args[]) throws IOException { Properties prop = new Properties(); OutputStream out = new FileOutputStream("D:\workspace\JavaStudy\src\test\test.properties");
/**
- 新增邏輯:
- 1.必須先讀取文件原有內容
2.增加新的記錄以后,再一起保存 */ //1.先讀取文件原有內容 Map toSaveMap = new HashMap(); Set keys = prop.keySet(); for(Iterator itr = keys.iterator(); itr.hasNext();){ String key = (String) itr.next(); Object value = prop.get(key); toSaveMap.put(key, value); } //2.增加你需要增加的屬性內容 toSaveMap.put("name", "zhang san"); toSaveMap.put("age", "25"); prop.putAll(toSaveMap); prop.store(out, "==== after add ====");
/**
修改邏輯:重新設置對應Key的值即可,非常簡單 */ prop.clear(); toSaveMap.put("name", "li si"); toSaveMap.put("age", "26"); prop.putAll(toSaveMap); prop.store(out, "==== after modify ====");
/**
刪除邏輯:找到對應的key,刪除即可 */
prop.clear(); toSaveMap.remove("name"); prop.putAll(toSaveMap); prop.store(out, "==== after remove ===="));/**
查詢邏輯: */ InputStream in = new FileInputStream("D:\workspace\JavaStudy\src\test\test.properties"); prop.load(in); System.out.println("name: " + prop.get("name")); System.out.println("age: " + prop.get("age"));
}</pre>