JAVA Properties读写配置文件

概述

Java中有一种配置文件是以.properties为后缀的文本文件,内部以键值对方式存储数据(key=value)

例子:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3308/douban
username=root
password=
#password=123456

行开头的#符号,是注释的意思

Properties类 就是Java中提供操作这种配置文件的类。

它继承于Hashtable类,也是键值对,但是它被封装了很多的方法,方便开发者操作properties配置文件。

线程安全的

构造方法

  • public Properties() :创建一个空的属性列表。

常用方法

  • load():加载一个properties配置文件
  • getProperty(key):获取key对应的值
  • setProperty(key, value):向配置文件中添加一组键值对
  • store(OutputStream out, String comments):将操作完配置文件保存成一个properties文件
  • stringPropertyNames() :所有键的名称的集合。

例子-读取文件

创建文件

在 src 目录下创建文件 db.properties,内容如下(UTF-8字符集):

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3308/scott?useSSL=false&useUnicode=true&characterEncoding=utf-8
username=root
password=
#password=root

注意:配置文件中,开头带有#的,是 注释,不会读取

代码

// 创建属性集对象
InputStream is = Thread.currentThread().getContextClassLoader()  
                    .getResourceAsStream("db.properties");
Properties pro = new Properties();
// 加载文本中信息到属性集
pro.load(fis);
// 遍历集合并打印
Set<String> strings = pro.stringPropertyNames();
for (String key : strings ) {
    System.out.println(key+" -- "+pro.getProperty(key));
}
fis.close();

例子-写文件

FileOutputStream fos=new FileOutputStream("config2.txt");
// 创建属性集对象
Properties properties = new Properties();
// 添加键值对元素
properties.setProperty("username", "root");
properties.setProperty("password", "12345");
properties.store(fos,"db config");
fos.close();

例子-读取java属性

Properties p=System.getProperties();
for(String key:p.stringPropertyNames()){
    System.out.println(key+"    =   "+p.getProperty(key));
}

原文出处:/show_1EF4sNINPvt3.html