Java IO流之Properties类的使用
目录
- 前言
- Properties类的基本介绍
- Properties类的常见方法
- 使用Properties类来读取配置文件mysql.properties
- 使用Properties类创建配置文件,修改配置文件内容
- 总结
前言
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();
propertwww.devze.comies.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=rootpwd=123456ip=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 N编程客栈ullPointerException();
}
// Makes sandroidure the key is not already in the h编程客栈ashtable.
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) {
www.devze.com 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("保存配置文件成功!");
}
}
创建的配置文件如下:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论