码迷,mamicode.com
首页 > 编程语言 > 详细

java 读取properties文件

时间:2014-12-30 18:30:47      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

在实际开发工作中,我们又是会将一些路径文件配置放在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")就行了。

java 读取properties文件

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!