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 }

 控制台输出:

 

转载于:https://www.cnblogs.com/arrrrrya/p/8029453.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值