Properties类和Properties文件
*.properties
是java支持的一种配置文件类型(所谓支持是因为Java提供了properties类,来读取properties文件中的信息)。文件中以键值对 "键=值
"的形式,存储工程中会多次重复使用的配置信息。随后,在需要用到这些配置信息,通过“Properties”类来读取这些信息,以实现“一次编写,多处调用;需要修改配置文件时,只修改一处即可”的效果。注意,其中的注释以#开始。
一、Properties文件
# MYSQL数据库配置文件
String driver="com.mysql.jdbc.Driver";//mysql提供的Driver接口的实现类
String jdbcUrl="jdbc:mysql:///user";//此处为"jdbc:mysql://localhost:3306/user"的简化形式,user为数据库名
String user="root";
String password="451535";
Connection conn= DriverManager.getConnection(jdbcUrl,user,password);
二、Properties类
1、创建 Properties 对象
Properties properties = new Properties();
2、添加属性
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");
3、获取属性值
password = prop.getProperty("password");
username = prop.getProperty("username");
4、从输入流中读取属性列表
properties.load(InputStream inStream)
5、按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)
properties.load(Reader reader)
6、将此 Properties 表中的属性列表(键和元素对)写入输出流
store(OutputStream out, String comments)
store(Writer writer, String comments)
try (OutputStream outputStream = new FileOutputStream("config.properties")) {
properties.store(outputStream, "My Configuration");
} catch (IOException e) {
e.printStackTrace();
}
7、迭代遍历 Properties 中的所有属性
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
// 处理每个属性...
}