zoukankan      html  css  js  c++  java
  • 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")就行了。

  • 相关阅读:
    分布式系统笔记
    Paxos算法细节详解(一)
    Java G1学习笔记
    Spring Boot 的 10 个核心模块
    k8s 重点
    毕玄:阿里十年,从分布式到云时代的架构演进之路
    netty原理解析
    JVM调优总结(一):基本概念
    《快学 Go 语言》第 16 课 —— 包管理 GOPATH 和 Vendor
    Oracle 检查表空间使用情况
  • 原文地址:https://www.cnblogs.com/mouseIT/p/4193982.html
Copyright © 2011-2022 走看看