Properties类示例

Java中Properties类用来处理有键值对的属性文件,利用它可以快速地把属性文件加载到内存,也可以快速把属性存放到文件中。它继承自hashTable类,除了拥有hashTable所有拥有的所有方法外,另外它还附加了用于与文件流操作的方法。

下面示例展示了Properties类的用法:

 1 public class PropertiesTest {
 2     public static void main(String[] args)throws Exception {
 3         
 4         Properties p = new Properties();
 5         
 6         p.setProperty("1", "one");
 7         p.setProperty("2", "two");
 8         p.setProperty("3", "three");
 9         //通过一个输出流,输出所有属性值
10         p.list(new PrintStream(System.out));
11         //存储到一个文件中
12         p.store(new FileOutputStream(new File("test.properties")), "说明");
13         //从一个文件中加载进来
14         p.load(new FileInputStream(new File("test.properties")));
15         //存储到一个xml文件中
16         p.storeToXML(new FileOutputStream(new File("test.xml")) , "说明");
17         //从一个xml文件中加载出来
18         p.loadFromXML(new FileInputStream(new File("test.xml")));
19         
20         System.out.println(p.getProperty("1"));
21         //没有的属性值,将返回null
22         System.out.println(p.getProperty("4"));
23         //如果没有些属性值 ,则返回设定的默认值
24         System.out.println(p.getProperty("4", "default four"));
25     }
26     
27     
28 
29 }

 

posted @ 2013-05-26 22:09  丁丁木木  阅读(169)  评论(0编辑  收藏  举报