当前位置: 移动技术网 > IT编程>开发语言>Java > 【Java】Properties文件的解析

【Java】Properties文件的解析

2019年04月18日  | 移动技术网IT编程  | 我要评论
 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 }

 

结果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网