# 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
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |