java中常量文件的配置与读取


java中常量文件的配置与读取:

 1 package com.floor.shop.user.util;
 2 
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.util.Enumeration;
 6 import java.util.HashMap;
 7 import java.util.Map;
 8 import java.util.Properties;
 9 
10 /**
11  * 课程笔记:http://www.cnblogs.com/newAndHui/category/1153640.html
12  * 疑问咨询wx:851298348
13  */
14 public class ConfigMapUtil {
15     private static Map<String, String> map = new HashMap<>();
16 
17     static {
18         try {
19             //读取文件流
20             InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
21             //转变为字符流
22             InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream,"utf-8");
23             //创建 Properties 对象
24             Properties properties = new Properties();
25            // prop.load(new InputStreamReader(in, "utf-8"));
26             //加载字符流
27             properties.load(inputStreamReader);
28             //获取所有key
29             Enumeration enumeration = properties.propertyNames();
30             while (enumeration.hasMoreElements()) {
31                 //遍历key
32                 String key = (String) enumeration.nextElement();
33                 //根据key取值
34                 String value = properties.getProperty(key);
35                 //放入map中
36                 map.put(key, value);
37             }
38         } catch (Exception e) {
39             e.printStackTrace();
40         }
41     }
42     public static String getShopWx() {
43         return map.get("shop.wx");
44     }
45     public static String getValueByKey(String key) {
46         return map.get(key);
47     }
48 
49     public static Map<String, String> getMap() {
50         return map;
51     }
52 
53     public static void setMap(Map<String, String> map) {
54         ConfigMapUtil.map = map;
55     }
56 
57 }
View Code

3.测试:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM