因为今天在项目中用到了该方法、作为一个小白、就顺手记下来当作笔记。
我们项目中是把这些静态资源、一些配置文件放在system.properties文件中,因为这些资源基本不会变动、并且很多地方都有引用到了,改变不易 。
废话不多、开始
1 public void InitSystem(){ 2 3 4 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 5 Properties properties = new Properties(); 6 7 InputStream in = null; 8 try{ 9 in = cl.getResourceAsStream("wechat.properties"); 10 properties.load(in); 11 for (Object o : properties.keySet()){ 12 Constants.wxProperties.put( o , properties.get(o)); 13 } 14 logger.info("加载微信配置文件完成..."); 15 16 properties = new Properties(); 17 in = cl.getResourceAsStream("redis.properties"); 18 properties.load(in); 19 for(Object o : properties.keySet()){ 20 Constants.redisProperties.put(o , properties.get(o)); 21 } 22 logger.info("加载redis配置文件完成..."); 23 24 25 26 }catch (IOException e){ 27 logger.error("[fail] load system properties failed" ); 28 e.printStackTrace(); 29 }finally { 30 if(in != null){ //在此处关闭流 31 try { 32 in.close(); 33 }catch (IOException e){ 34 logger.error("[error] a error happened in close inputStream "); 35 e.printStackTrace(); 36 } 37 } 38 } 39 40 }
而在上面的Contstants.wxPropertis是定义在公用文件中的
1 public class Constants{ 2 /** 3 * 加载微信基本信息 4 */ 5 public static Map<Object , Object> wxProperties = new HashMap<Object, Object>(); 6 7 8 /** 9 * 加载redis配置文件 10 */ 11 public static Map<Object , Object> redisProperties = new HashMap<Object, Object>(); 12 13 14 }
这样我们就可以在加载系统文件的时候把这些加载在内存中、然后后面再用到的时候、直接用就好了。