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