import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.HashMap;import java.util.Map;import java.util.Properties;import java.util.Set; import org.junit.Test; public class PropertiesTest { public static void main(String[] args) { } /** * 刪除設定檔中的key * @throws IOException * */ @Test public void delete() throws IOException{ Properties properties = new Properties(); File file = new File("test.properties"); FileInputStream fis = new FileInputStream(file); properties.load(fis); //必須先用map將所有的內容先儲存,不然一刪除,原來的內容都沒了 Map<String, String> map = new HashMap<String, String>(); Set<Object> keySet = properties.keySet(); System.out.println(keySet.size()); for (Object object : keySet) { String key = (String) object; String value = (String) properties.get(key); System.out.println(key+"="+value); map.put(key, value); } //刪除key map.remove("age3"); properties.remove("age3"); for (java.util.Map.Entry<String, String> entry: map.entrySet()) { properties.setProperty(entry.getKey(), entry.getValue()); } FileOutputStream fos = new FileOutputStream(file); properties.store(fos, "刪除設定檔中的key:age3"); fos.close(); fis.close(); } /** * 對設定檔的修改 * @throws IOException */ @Test public void update() throws IOException{ Properties properties = new Properties(); File file = new File("test.properties"); FileInputStream fis = new FileInputStream(file); properties.load(fis); //必須先用map將所有的內容先儲存,不然一更新,原來的內容都沒了 Map<String, String> map = new HashMap<String, String>(); Set<Object> keySet = properties.keySet(); System.out.println(keySet.size()); for (Object object : keySet) { String key = (String) object; String value = (String) properties.get(key); System.out.println(key+"="+value); map.put(key, value); } map.put("name", "李四"); map.put("age", "222"); map.put("age3", "222"); for (java.util.Map.Entry<String, String> entry: map.entrySet()) { properties.setProperty(entry.getKey(), entry.getValue()); } FileOutputStream fos = new FileOutputStream(file); properties.store(fos, "更新設定檔"); fos.close(); fis.close(); } /** * 向設定檔寫入內容 * @throws IOException */ @Test public void write() throws IOException { Properties properties = new Properties(); String file = "aa.properties"; FileOutputStream fos = new FileOutputStream(file); properties.setProperty("aa", "123"); properties.setProperty("bb", "456"); properties.setProperty("cc", "789"); properties.setProperty("name", "張三"); properties.store(fos, "儲存檔案"); fos.close(); } /** * 讀取設定檔 * @throws IOException */ @Test public void read() throws IOException{ Properties properties = new Properties(); File file = new File("test.properties"); FileInputStream fis = new FileInputStream(file); properties.load(fis); Set<Object> keySet = properties.keySet(); for (Object object : keySet) { System.out.println(object.toString()+"="+properties.getProperty(object.toString())); } } }
|