读取配置文件

 
第一种方式
importorg.apache.commons.configuration.ConfigurationException;
importorg.apache.commons.configuration.PropertiesConfiguration;
importorg.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
public class cshi {
     public static void main(String[] args) {
           System.out.println(getProperty("A1"));
     }
     private static PropertiesConfiguration config;
     static {
           try {
                config = new PropertiesConfiguration();
                config.setEncoding("UTF-8"); //先设置编码在加载文件
                config.load("sss.properties");
           } catch (ConfigurationException e) {
                e.printStackTrace();
           }
           // 设置reload策略,这里用当文件被修改之后reload(默认5s中检测一次)
           FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
           strategy.setRefreshDelay(20000);
           config.setReloadingStrategy(strategy);
     }
     public static synchronized String getProperty(String key) {
           return (String) config.getProperty(key);
     }
}
 
//第二种方式:
public static String readProperties(String key) {
           // 读取信息文件
           ClassPathResource cr = new ClassPathResource("pay.properties");// 会重新加载spring框架
           Properties pros = new Properties();
           try {
                pros.load(cr.getInputStream());
           } catch (IOException ex) {
                System.out.println("读取信息文件错误");
           }
           String url = pros.getProperty(key);
           return url;
     }

 

posted @ 2018-06-14 10:48  jwcc  阅读(138)  评论(0编辑  收藏  举报