package FileDemo; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; public class PropertiesFunctions { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { /* * Map |--Hashtable |--Properties: * * Properties集合: 特點: 1,該集合中的鍵和值都是字符串類型。 2,集合中的數據可以保存到流中,或者從流獲取。 * * 通常該集合用於操作以鍵值對形式存在的配置文件。 */ test(); myLoad(); method_1(); method_2(); } private static void method_2() {//Property集合的簡單使用 Properties prop=new Properties(); prop=System.getProperties(); prop.list(System.out); } private static void method_1() throws IOException {// Store方法演示 Properties prop = new Properties(); prop.setProperty("wangwu", "12"); prop.setProperty("ciugwu", "25"); prop.setProperty("zhangsan", "32"); prop.setProperty("liuxiao", "36"); FileOutputStream fos = new FileOutputStream("D:\\info1.txt"); prop.store(fos, "info"); fos.close(); } private static void myLoad() throws IOException {// 模擬Property集合的load方法 Properties prop = new Properties(); BufferedReader bufr = new BufferedReader(new FileReader("D:\\info.txt")); String line = null; while ((line = bufr.readLine()) != null) { if (line.startsWith("#")) { continue; } String arr[] = line.split("="); prop.setProperty(arr[0], arr[1]); } prop.list(System.out); bufr.close(); } private static void test() throws IOException { // 對已有的配置文件中的信息進行修改。 /* * 讀取這個文件。 並將這個文件中的鍵值數據存儲到集合中。 在通過集合對數據進行修改。 在通過流將修改后的數據存儲到文件中。 */ File file = new File("D:\\info.txt"); if (!file.exists()) { file.createNewFile(); } FileReader fr = new FileReader(file); // 創建集合存儲配置信息 Properties prop = new Properties(); prop.load(fr); prop.setProperty("wangwu", "16"); FileWriter fw = new FileWriter(file); prop.store(fw, ""); prop.list(System.out); fw.close(); fr.close(); } }