【Java】Properties文件的解析

 1 public abstract class ReadProperties {
 2 
 3     public ReadProperties() {}
 4     
 5     /**
 6      * 回调函数,由调用者处理
 7      * @param key
 8      * @param value
 9      */
10     public abstract void dealKeyAndValue(String key, String value);
11     
12     /**
13      * 根据包路径解析
14      * @param packagePath
15      * @throws IOException
16      */
17     public void read(String packagePath) throws IOException {
18         InputStream is = this.getClass().getResourceAsStream(packagePath);
19         read(is);
20     }
21     
22     /**
23      * 根据文件的绝对路径解析
24      * @param absolutePath
25      * @throws IOException
26      */
27     public void readFile(String absolutePath) throws IOException {
28         read(new File(absolutePath));
29     }
30     
31     /**
32      * 根据{@link File}解析
33      * @param file
34      * @throws IOException
35      */
36     public void read(File file) throws IOException {
37         read(new FileInputStream(file));
38     }
39     
40     /**
41      * 根据{@link InputStream}解析
42      * @param is
43      * @throws IOException
44      */
45     public void read(InputStream is) throws IOException {
46         Properties properties = new Properties();
47         try {
48             // Properties文件会出现乱码问题,以UTF-8的方式打开
49             properties.load(new InputStreamReader(is, "UTF-8"));
50             Enumeration<Object> keys = properties.keys();
51             
52             while (keys.hasMoreElements()) {
53                 String key = (String) keys.nextElement();
54                 String value = properties.getProperty(key);
55                 properties.get(key);
56                 
57                 dealKeyAndValue(key, value);
58             }
59         } finally {
60             is.close();
61         }
62     }
63         
64 }

 

使用:
在src下新建一个test.properties文件如下:

 

执行解析:

 1 public class Test {
 2 
 3     public static void main(String[] args) throws Exception {
 4         new ReadProperties() {
 5             @Override
 6             public void dealKeyAndValue(String key, String value) {
 7                 System.out.println(key + " = " + value);
 8             }
 9         }.read("/test.properties");;
10     }
11 
12 }

 

结果如下:

posted @ 2019-04-17 17:36  松饼人  阅读(676)  评论(0编辑  收藏  举报