1、Properties类

Properties类表示了一个持久的属性集。Properties可保存在流中或从流中加载,属性列表中的key和value必须是字符串。

2、主要方法

load(InputStream in)  从输入流读取属性列表
getProperties(String key)  获取指定key的值,返回string
setProperty(String key, String value)  设置或修改属性的值
store(OutputStream out, String comments)  将properties对象写入一个输出流,comments为注释,comments为空则不加注释

下面进行代码演示

1 /*初始配置文件2 aa=13 bb=24 cc=35 */
6
7 Properties prop = new Properties(); //创建Properties对象
8 InputStream in = null;9 FileOutputStream oFile = null;10 try{11 in = new FileInputStream("filePath"); //创建输入流文件对象
12 prop.load(in); //加载输入流
13 System.out.println("aa=" + prop.getProperty("aa")); //aa=1
14 prop.setProperty("aa", "11"); //修改"aa"的值
15 oFile = new FileOutputStream("filePath"); //创建输出流文件对象
16 prop.store(oFile, ""); //将Properties对象的属性保存到输出流指定文件
17 } catch(IOException e) {18 log.error(e);19 } finally{20 try{21 oFile.close(); //关闭输出流
22 } catch(IOException e) {23 log.error(e);24 }25 try{26 in.close(); //关闭输入流
27 } catch(IOException e) {28 log.error(e);29 }30 }

最后的关闭IO流很重要,一定要放在finally代码块中执行。

3、修改properties配置文件时遇到的一些问题

读取配置文件一般不会出什么问题,修改和写入的时候稍微复杂一点,把遇到的问题记录一下

3.1 配置FileOutputStream的第二个参数true,导致配置文件末尾重复追加配置项

FileOutputStream构造函数

FileOutputStream(String name, boolean append)

append代表是否向文件末尾追加字符流的形式写入文件,默认为false,即重新写入配置

此处的输出流配置第二个参数为true会导致不停的在配置文件末尾追加重复的配置,导致输出流指定的文件越来越大。所以最好不加这个参数

1 /*初始配置文件2 aa=13 bb=24 cc=35 */
6
7 Properties prop = newProperties();8 InputStream in = new FileInputStream("filePath");9 prop.load(in);10 prop.setProperty("aa", "11");11 FileOutputStream oFile = new FileOutputStream("filePath", true);12 prop.store(oFile, "");13
14 /*执行后配置文件15 aa=116 bb=217 cc=318
19 aa=1120 bb=221 cc=322 */
3.2 FileOutputStream创建位置导致诡异事情

主要是与setProperty()方法的相对位置

正常是先setProperty()设置属性,然后创建FileOutputStream对象

1 /*初始配置文件2 aa=13 bb=24 cc=35 */
6
7 //正常写法
8 InputStream in = new FileInputStream("filePath");9 prop.load(in);10 prop.setProperty("aa", "11");11 FileOutputStream oFile = new FileOutputStream("filePath");12 prop.store(oFile, "");13
14 //问题写法
15 InputStream in = new FileInputStream("filePath");16 FileOutputStream oFile = new FileOutputStream("filePath"); //提前创建17 prop.load(in);18 prop.setProperty("aa", "11");19 prop.store(oFile, "");20
21 /*正常执行后的配置文件22 aa=1123 bb=224 cc=325 */
26
27 /*问题执行后的配置文件28 aa=1129 */

如果反过来,会导致除setProperty()修改的属性,其它都会丢失。

没想明白这是为什么,有人明白可以指点一下。

3.3 读取和修改properties文件后改变文件内容顺序

使用jdk提供的Properties类读取和修改配置文件后,加载到内存中的顺序是随机的,不能保证和原文件的顺序一致,因此需要重写Properties类,实现顺序读取properties属性。