Properties类简单介绍
1、Properties 类以key-value(键值对)形式存放数据
格式为:
键=值
键=值
注意:键值对不能有空格,值不需要加引号,默认类型为String
2、key不允许重复,value可以重复,都可以取任意类型的数据,但是都不能为null
3、主要用于从 xxx.properties 文件中加载数据到Properties类对象中进行读取和修改,用作配置文件
Properties 类的常用方法:
load:加载配置文件的键值对到Properties对象
list:将数据显示到指定设备
getProperty(key):根据键获取值
setProperty(key,value):设置键值对到Properties对象
store:将Properties中的键值对存储到配置文件中,在idea软件中,保存信息到配置文件如果含有中文,会保存为对应的unicode码值
代码示例:
import java.io.*;
import java.util.Properties;
/**
* 使用Properties 类来 保存 、 读取 mysql.properties 文件
*/
public class Properties02 {
public static void main(String[] args) throws IOException {
//1. 创建Properties 对象
Properties properties = new Properties();
//设置键值对k-v到Properties对象
properties.setProperty("ip", "196.168.1.1");
properties.setProperty("user", "root汤姆");//注意,保存时,默认是中文的 unicode码值
properties.setProperty("pwd", "888888");
//将k-v 存储文件中
properties.store(new FileOutputStream("src\\mysql.properties"), null);//注意保存时,默认是中文的 unicode码值
//设置保存数据的编码方式
// properties.store(new OutputStreamWriter(new FileOutputStream("src\\mysql.properties"), "gbk"), null);
System.out.println("保存配置文件成功~");
//2. 加载指定配置文件
// properties.load(new FileReader("src\\mysql.properties"));//字符方式
// properties.load(new FileInputStream("src\\mysql.properties"));//字节方式
properties.load(new InputStreamReader(new FileInputStream("src\\mysql.properties"), "gbk"));//指定字符编码方式
//3. 把k-v显示控制台
properties.list(System.out);
//4. 根据key 获取对应的值
System.out.println("====根据key 获取对应的值====");
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名=" + user);
System.out.println("密码是=" + pwd);
}
}