前言
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("保存配置文件成功!");
}
}创建的配置文件如下:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论