前言:
Properties类的基本介绍:
Properties类的常见方法如下:
一、使用Properties类来读取配置文件mysql.properties,具体代码如下:
mysql.properties配置文件中具体内容如下:
/**
* 使用Properties类来读取mysql.properties文件
*/
public class Properties02 {
public static void main(String[] args) throws IOException {
//1.创建Properties对象
Properties properties = new Properties();
properties.load(new FileReader("src\\mysql.properties"));
//3.把键值对 显示到控制台
properties.list(System.out);
System.out.println("--------------------")
//根据key 获取对应的值
String pwd = properties.getProperty("pwd");
String user = properties.getProperty("user");
System.out.println("用户名:" + user);
System.out.println("密码:" + pwd);
}
}
结果如下:
-- listing properties --
user=root
pwd=123456
ip=192.168.100.100
--------------------
用户名:root
密码:123456
二、使用Properties类 创建配置文件,修改配置文件内容,具体代码如下:
/**
* 使用Properties类 创建配置文件,修改配置文件内容
*/
public class Properties03 {
public static void main(String[] args) throws IOException {
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); //如果是新key,就添加
return null;
}
*/
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");
properties.setProperty("pwd", "888");
//store()方法的第二个参数,表示注释
properties.store(new FileOutputStream("src\\mysql2.properties"), "hello");
System.out.println("保存配置文件成功!");
}
}
创建的配置文件如下: