**# Properties類** - **基本介紹** ![](https://img2023.cnblogs.com/blog/3008601/202306/3008601-20230604103622859-1793594469.png) 1. 專門用於讀寫配置文件的集合類 配置文件的格式: ...
# Properties類
-
基本介紹
-
專門用於讀寫配置文件的集合類
配置文件的格式:
鍵=值
鍵=值
-
註意:鍵值對不需要有空格,值不需要用引號一起來。預設類型是String。
-
Properties的常見方法
- load:載入配置文件的鍵值對 到Properties對象;
- list:將數據顯示到指定設備/流對象;
- getProperty(key):根據鍵獲取值;
- setProperty(key, value):設置鍵值對到Properties對象;
- store:將Properties中的鍵值對存儲到配置文件,在idea中,保存信息到配置文件,如果含有中文,會存儲為unicode碼;
-
-
讀文件
示例文件:mysql.properties
ip=192.168.100.100 user=root pwd=12345
代碼演示:
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * @author: 86199 * @date: 2023/5/8 20:06 * @description: */ public class Properties02 { public static void main(String[] args) throws IOException { //使用Properties類 來讀取mysql.properties 文件 //1. 創建Properties對象 Properties properties = new Properties(); //2. 載入指定配置文件 properties.load(new FileReader("src\\mysql.properties")); //3. 把 k-v 顯示到控制台 properties.list(System.out); //4. 根據key獲取對應的值 String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); System.out.println("用戶名 = " + user); System.out.println("密碼 = " + pwd); } } /* 運行結果: -- listing properties -- user=root pwd=12345 ip=192.168.100.100 root 12345 */
-
修改文件
import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; /** * @author: 86199 * @date: 2023/5/8 20:52 * @description: */ public class Properties03 { public static void main(String[] args) throws IOException { //load載入的時候載入到properties對象,是繼承了hashtable的, // 所以相同key的就替換value了 //使用Properties類 來創建 配置文件,修改配置文件內容 Properties properties = new Properties(); //創建 //1. 如果該文件沒有這個key,就是創建 //2. 如果該文件有這個key,就是修改 /* Properties 父類是 Hashtable,底層就是Hashtable 核心方法 public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value;//如果 key 存在,就替換 return old; } } addEntry(hash, key, value, index);//如果是新k,就addEntry return null; } */ properties.setProperty("charset", "utf8"); properties.setProperty("user","湯姆");//註意中文保存時,是保存中文的 unicode碼 properties.setProperty("pwd","888888"); //將k-v 存儲到文件中即可 properties.store(new FileOutputStream("src\\mysql2.properties"), null); System.out.println("保存配置文件成功~~"); } }
mysql2.properties文件內容:
#Mon May 08 21:16:41 CST 2023 user=\u6C64\u59C6 pwd=888888 charset=utf8