使用JAVA格式将属性保存到文件中

8
有没有一种方法可以使用Properties对象在Java中保存一些格式化的属性?比如,是否有一种方式在条目之间引入新行?或者在每个键之前添加注释?
我知道这可以很容易地通过常规I/O实现,但是想知道是否有一种使用属性对象的方法。
5个回答

20

在每组属性之间编写注释的关键是将它们存储在多个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

这将给我所需的所有控制权。使用不同的属性对象,我可以添加我想要的注释并按照我想要的顺序存储它们。谢谢! - javydreamercsw

2

2
请在此处插入您的答案的主要要点,以便在链接失效时仍然可以找到答案。谢谢! - Samoth

0

不行。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. 

另一方面,您可以使用Properties对象作为数据源,在属性文件中提供编写额外行和注释的指令。

0

这个类 CommentedProperties

将解析属性

 ## 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

很好,但完全与所要求的相反:P - javydreamercsw

0

Properties 对象本身不保留有关其在文件中保存的结构的任何详细信息。它只有一个数据映射,这实际上意味着它甚至不必按照读取顺序编写它们。您将需要使用普通 I/O 来保持格式并进行所需更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接