java 读取properties文件

在实际开发工作中,我们又是会将一些路径文件配置放在properties文件中,这样我们需要修改路径的时候就只需要写该一下配置文件就行了,不需要在代码中挨个挨个的去改。但是我们怎样获得配置文件中的值呢?其实这个很简单,我们只需要封装如下一个工具类就行了:

public class UrlUtil {
    private static Properties config = null;

     static {
          InputStream in = UrlUtil.class.getClassLoader().getResourceAsStream("url.properties");
          config = new Properties();     
           try {
            config.load(in);
            in.close();
          } catch (IOException e) {
            //读取url.properties出错
            e.printStackTrace();
         }  
     }
     
      /**
       * 通过键获得对应的值
       * @param key
       * @return
       */
     public static String getValue(String key) {
      try {
       String value = config.getProperty(key);
       return value.trim();
      } catch (Exception e) {
       e.printStackTrace(); 
       return null;
      }
     }

     /**
      * 读取properties的全部信息*/
     public static void getAllProperties() {
      try {
       Enumeration en = config.propertyNames();
       while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        String Property = config.getProperty(key);
       }
      } catch (Exception e) {
        e.printStackTrace();
        System.err.println("ConfigInfoError" + e.toString());
      }
     }
     public static void main(String args[]) {
      
     }
}

代码中的url.properties就是我们放置路径的配置文件。比如我们的url.properties中有个图片路径:imgPath=c:/images

我们要取得这个值只需要使用:UrlUtil.getValue("imgPath")就行了。

原文地址:https://www.cnblogs.com/mouseIT/p/4193982.html