java 配置在.properties文件中的常量


不讓用常量類,那就用.properties文件配置,放在根目錄。

 

 1 import java.util.HashMap;
 2 import java.util.Iterator;
 3 import java.util.Map;
 4 import java.util.Properties;
 5 
 6 /**
 7  * Created by syl on 2017/12/12 0007. 讀取常量properties文件
 8  */
 9 public class PropertyUtil {  
10     @SuppressWarnings("rawtypes")
11     private static Map map = null;  
12   
13     @SuppressWarnings({ "rawtypes", "unchecked" })
14     private static void loadFile() {  
15         map = new HashMap();  
16         try {  
17             Properties p = new Properties();  
18             p.load(PropertyUtil.class.getClassLoader().getResourceAsStream("params.properties"));  
19             Iterator it = p.keySet().iterator();  
20             while (it.hasNext()) {  
21                 String key = (String) it.next();  
22                 String value = p.getProperty(key);  
23                 map.put(key, value);  
24             }  
25         } catch (Exception e) {  
26             e.printStackTrace();  
27         }  
28     }  
29   
30     public static String getValue(String str) {  
31         if (map == null) {  
32             loadFile();  
33         }  
34         return (String) map.get(str);  
35     }  
36     
37     public static void main(String[] args) {
38         String s = PropertyUtil.getValue("test");
39         System.out.println(s);
40     }
41 }

 控制台輸出:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM