Properties类和Properties文件

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);
    // 处理每个属性...
}

参考文献

Properties类的用法总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值