Properties属性文件

 1 package com.jdk7.chapter4;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.util.Properties;
 8 
 9 public class PropertiesTest {
10     public static void main(String[] args) throws IOException {
11         Properties prop1 = new Properties();
12         prop1.setProperty("001", "ssss");
13         prop1.setProperty("004", "tttt");
14         prop1.setProperty("003", "jjjj");
15         prop1.setProperty("002", "pppp");
16         prop1.setProperty("002", "rrrr");    //Properties不允许key重复,如果重复则采用最后一组
17         System.out.println("001: "+prop1.getProperty("001"));
18         System.out.println("004: "+prop1.getProperty("004"));
19         System.out.println("003: "+prop1.getProperty("003"));
20         System.out.println("002: "+prop1.getProperty("002"));
21         System.out.println("other: "+prop1.getProperty("other1", "none"));  //不存在的key返回默认值
22         
23         String fileName1 = "D:/software/eclipse/workspace/JDK7/src/com/jdk7/chapter4/testout.properties";
24         String fileName2 = "D:/software/eclipse/workspace/JDK7/src/com/jdk7/chapter4/testin.properties";
25         FileOutputStream out = new FileOutputStream(fileName1);
26         prop1.store(out, "test");
27         out.close();
28         
29         FileInputStream in = new FileInputStream(fileName2);
30         prop1.load(in);
31         in.close();
32         System.out.println("username: "+prop1.getProperty("username"));
33         System.out.println("password: "+prop1.getProperty("password"));
34         
35         prop1.list(System.out);        //将Properties中的数据输出到一个输出流中
36     }
37 }
38 
39 执行结果:
40 001: ssss
41 004: tttt
42 003: jjjj
43 002: rrrr
44 other: none
45 username: admin
46 password: 123
47 -- listing properties --
48 password=123
49 004=tttt
50 003=jjjj
51 002=rrrr
52 001=ssss
53 username=admin

 

posted @ 2018-02-22 16:39  celineluo  阅读(458)  评论(0编辑  收藏  举报