有没有一种方法可以使用Properties对象在Java中保存一些格式化的属性?比如,是否有一种方式在条目之间引入新行?或者在每个键之前添加注释?
我知道这可以很容易地通过常规I/O实现,但是想知道是否有一种使用属性对象的方法。
我知道这可以很容易地通过常规I/O实现,但是想知道是否有一种使用属性对象的方法。
在每组属性之间编写注释的关键是将它们存储在多个Properties
对象中。
例如:
FileOutputStream fos = new FileOutputStream("c:/myconfig.property");
Properties prop = new Properties();
prop.put("com.app.port", "8080");
prop.put("com.app.ip", "127.0.0.1");
prop.store(fos, "A Test to write properties");
fos.flush();
Properties prop2 = new Properties();
prop2.put("com.app.another", "Hello World");
prop2.store(fos, "Where does this go?");
fos.flush();
fos.close();
这将会产生如下输出:
#A Test to write properties
#Fri Apr 08 15:28:26 ADT 2011
com.app.ip=127.0.0.1
com.app.port=8080
#Where does this go?
#Fri Apr 08 15:28:26 ADT 2011
com.app.another=Hello World
不行。Properties元素怎么知道在每个键之前写什么注释?
你可以在Properties.store( Writer, String )时包含文件级别的注释。在那个注释和时间戳注释之后:
Then every entry in this Properties table is written out, one per line.
For each entry the key string is written, then an ASCII =, then the associated
element string. For the key, all space characters are written with a
preceding \ character. For the element, leading space characters, but not
embedded or trailing space characters, are written with a preceding \ character.
The key and element characters #, !, =, and : are written with a preceding
backslash to ensure that they are properly loaded.
将解析属性
## General comment line 1
## General comment line 2
##!General comment line 3, is ignored and not loaded
## General comment line 4
# Property A comment line 1
A=1
# Property B comment line 1
# Property B comment line 2
B=2
! Property C comment line 1
! Property C comment line 2
C=3
D=4
# Property E comment line 1
! Property E comment line 2
E=5
# Property F comment line 1
#!Property F comment line 2, is ignored and not loaded
! Property F comment line 3
F=5
属性文件的注释如下:
General comment line 1
General comment line 2
General comment line 4
因此,属性“A”的注释是:
Property A comment line 1
因此,属性“B”的注释是:
Property B comment line 1
Property B comment line 2
所以属性“C”
Property C comment line 1
Property C comment line 2
因此,属性“D”的注释为空。
因此,属性“E”的注释为:
Property E comment line 1
Property E comment line 2
因此,属性“F”的注释为:
Property F comment line 1
Property F comment line 3
Properties
对象本身不保留有关其在文件中保存的结构的任何详细信息。它只有一个数据映射,这实际上意味着它甚至不必按照读取顺序编写它们。您将需要使用普通 I/O 来保持格式并进行所需更改。