首页 > 编程语言 > 详细

【Java】Properties文件的解析

时间:2019-04-17 17:57:43      阅读:134      评论:0      收藏:0      [点我收藏+]
 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 }

 

结果如下:

技术分享图片

【Java】Properties文件的解析

原文:https://www.cnblogs.com/a526583280/p/10725026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!