0

0

读取配置文件properties并解析xml的main方法

零下一度

零下一度

发布时间:2017-06-25 10:33:23

|

2768人浏览过

|

来源于php中文网

原创

在项目中,我们经常将配置文件写为xml格式,并在properties文件里,给出xml文件路径。

对于properties文件读取,这里给出propertyUtil工具类。

  在这之前,请注意:Java 的 Properties 加载属性文件后是无法保证输出的顺序与文件中一致的,因为 Properties 是继承自 Hashtable 的, key/value 都是直接存在 Hashtable 中的,而 Hashtable 是不保证进出顺序的。

  解决办法:继承java.util.Properties类,用LinkedHashSet 来保存它的所有 key。

OrderedProperties类如下

package com.test;import java.util.Collections;import java.util.Enumeration;import java.util.LinkedHashSet;import java.util.Properties;import java.util.Set;public class OrderedProperties extends Properties{private static final long serialVersionUID = 1L;    private final LinkedHashSet keys = new LinkedHashSet();  
       public Enumeration keys() {  return Collections. enumeration(keys);  
    }  
   public Object put(Object key, Object value) {  
        keys.add(key);  return super.put(key, value);  
    }  
   public Set keySet() {  return keys;  
    }  
   public Set stringPropertyNames() {  
        Set set = new LinkedHashSet();  
   for (Object key : this.keys) {  
            set.add((String) key);  
        }  
   return set;  
    }  

}

读取配置文件properties并解析xml的main方法:

package com.test;public class T {public static void main(String[] args) {// 加载properties文件propertityUtil pu = propertityUtil.getInstance("project-config.properties");// 得到业务配置文件的路径String WorkConfigureFile = pu.getProperty("WorkConfigureFile");// 解析该xml文件ConfigureFileFw configureFileFw = new ConfigureFileFw();
        configureFileFw.parseConfigXmlFile(WorkConfigureFile);
        
        
    }
}

propertityUtil类如下

STORYD
STORYD

帮你写出让领导满意的精美文稿

下载
  1 package com.test;  2   3 import java.io.FileInputStream;  4 import java.io.FileNotFoundException;  5 import java.io.FileOutputStream;  6 import java.io.IOException;  7 import java.io.OutputStream;  8   9 public class propertityUtil { 10  11     /** 12      * prop对像 13      */ 14     private OrderedProperties prop = null; 15  16     /** 17      * 配置文件位置,默认为***-config.properties 18      */ 19     private String CONFIGPATH = "project-config.properties"; 20  21     /** 22      * 构造函数 23      */ 24     public propertityUtil() { 25         init(); 26     } 27  28     /** 29      * 构造函数 30      * 
 31      * @param prop 32      *            prop对像 33      */ 34     public propertityUtil(OrderedProperties prop) { 35         this.prop = prop; 36     } 37  38     /** 39      * 构造函数 40      * 
 41      * @param conf 42      */ 43     public propertityUtil(String conf) { 44         this.CONFIGPATH = conf; 45         init(CONFIGPATH); 46     } 47  48     /** 49      * 取得属性 50      * 
 51      * @return 52      */ 53     public OrderedProperties getProp() { 54         return prop; 55     } 56  57     /** 58      * 设置属性 59      * 
 60      * @param prop 61      */ 62     public void setProp(OrderedProperties prop) { 63         this.prop = prop; 64     } 65  66     /** 67      * 实例 68      * 
 69      * @param configpath 70      * @return 71      */ 72     public static propertityUtil getInstance(String configpath) { 73         return new propertityUtil(configpath); 74     } 75  76     /** 77      * 读取属性文件 78      * 
 79      * @param configpath 80      */ 81     private void init(String configpath) { 82         this.CONFIGPATH = configpath; 83         init(); 84     } 85  86     /** 87      * 初始化prop,从文件中读取 88      */ 89     private void init() { 90         if (this.CONFIGPATH == null || this.CONFIGPATH.length() == 0) { 91             System.out.println("No configFile"); 92         } else { 93  94             String srcDir = System.getProperty("user.dir"); 95             srcDir = srcDir + "/resources/properties/" + this.CONFIGPATH; 96             prop = new OrderedProperties(); 97             FileInputStream fin = null; 98             try { 99                 fin = new FileInputStream(srcDir);100                 prop.load(fin);101             } catch (FileNotFoundException e2) {102                 e2.printStackTrace();103             } catch (IOException e2) {104                 e2.printStackTrace();105             }106 107             // InputStream is = getClass().getResourceAsStream(this.CONFIGPATH);108             // prop = new Properties();109             // try {110             // prop.load(is);111             // } catch (Exception e) {112             // e.printStackTrace();113             // }114         }115     }116 117     /**118      * 取得属性值类119      * 
120      * @param propName121      * @return122      */123     public String getProperty(String propName) {124124         return getProperty(propName, "");125     }126 127     /**128      * 取得属性值类129      * 
130      * @param propName131      * @return132      */133     public String getProperty(String propName, String defValue) {134         if (prop == null)135             init();136         String s = defValue;137         try {138             s = prop.getProperty(propName);139             if (s == null) {140                 s = defValue;141             } else {142                 s = s.trim();143             }144         } catch (Exception e) {145             e.printStackTrace();146         }147         return s;148     }149 150     /**151      * 设置属性152      * 
153      * @param propName154      * @param value155      */156     public void setProperty(String propName, String value) {157         if (prop == null)158             init();159         try {160             prop.setProperty(propName, value);161             storeProperty();162         } catch (Exception e) {163             e.printStackTrace();164         }165     }166 167     /**168      * 保存属性文件169      */170     private void storeProperty() {171         try {172             String path = prop.getProperty("path");173             OutputStream out = new FileOutputStream(path);174             prop.store(out, " -- sl Soft Config File -- ");175             out.close();176         } catch (Exception ioe) {177             ioe.printStackTrace();178         }179     }180 }
View Code

xml解析类

  1 package com.test;  2   3 import java.io.File;  4 import java.util.HashMap;  5 import java.util.List;  6 import java.util.Map;  7 import org.dom4j.Document;  8 import org.dom4j.Element;  9 import org.dom4j.io.SAXReader; 10  11 /** 12  * 业务方法配置管理类 13  * @author  14  * 15  */ 16 public class ConfigureFileFw { 17      18     /** 19      * 业务方法配置Map 20      */ 21     private static Map> workAttributes = new HashMap>(); 22      23     private Document document = null; 24      25     private Element rootElement = null; 26      27     /** 28      * 获取所有业务 29      * @return 30      */ 31     public Map> getWorkAttributes() { 32         return workAttributes; 33     } 34     /** 35      * 根据world获取对应业务 36      * @return 37      */ 38     public Map getWorkAttributesByWorkId(String workId) { 39         return workAttributes.get(workId); 40     } 41      42     /** 43      * 判断是否包含该业务 44      * @param workId 45      * @return 46      */ 47     public String hasWorkId(String workId) { 48         //Modified by wxq 2016/12/29 49         //return workAttributes.containsKey(workId); 50         String temp = ""; 51         for(String configWorkId:workAttributes.keySet()){ 52             if (configWorkId.contains(".*")){ 53                 temp = configWorkId.substring(0,configWorkId.indexOf(".")); 54             } 55             else{ 56                 temp  = configWorkId; 57             } 58             if(workId.contains(temp)){ 59                 return configWorkId; 60             } 61         } 62         return ""; 63         //Ended by wxq 2016/12/29 64          65     } 66     /** 67      * 根据业务名称获取业务 68      * @param workName 69      * @return 70      */ 71     public  Map getWorkAttributesByWorkName(String workName) { 72          73         for (String str : workAttributes.keySet()) { 74             Map temp = workAttributes.get(str); 75             if (temp.get("name").equals(workName)) { 76                 return temp; 77             } 78         } 79         return null; 80     } 81     //加入业务方法 82     private void addToWorkAttributes(String workId, Map attrMap) { 83         workAttributes.put(workId, attrMap); 84     } 85     /** 86      * 根据传入的配置文件,初始化所有业务 87      * @param fileName 88      */ 89     public void parseConfigXmlFile(String fileName) { 90         try { 91             File f = new File(fileName); 92             SAXReader reader = new SAXReader(); 93             Document doc = reader.read(f); 94             rootElement = doc.getRootElement(); 95             if (!rootElement.equals(null)) { 96                 Element works = (Element)rootElement.element("works"); 97                 List workList = works.elements(); 98                 for (int i = 0; i < workList.size(); i++) { 99                     Element work = (Element) workList.get(i);100                     String workID = work.elementText("id");101                     String workName = work.elementText("name");102                     String workDescription = work.elementText("description");103                     String workMethod = work.elementText("method");104                     String dll = work.elementText("dll");105                     String class1 = work.elementText("class");106                     String workSend = work.elementText("send");107                     String workReceive = work.elementText("receive");108 109                     Map workAttrMap = new HashMap();110                     workAttrMap.put("id", workID);111                     workAttrMap.put("name", workName);112                     workAttrMap.put("description", workDescription);113                     workAttrMap.put("method", workMethod);114                     workAttrMap.put("dll", dll);115                     workAttrMap.put("class", class1);116                     workAttrMap.put("send", workSend);117                     workAttrMap.put("receive", workReceive);118                     workAttributes.put(workID, workAttrMap);119                 }120             }121             122         } catch (Exception e) {123             System.out.println("exception:" + e.getMessage());124124         }125     }126 127 }
View Code

 

 

  

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

4

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

7

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

42

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

4

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

3

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
CSS3 教程
CSS3 教程

共18课时 | 4.1万人学习

Git 教程
Git 教程

共21课时 | 2.3万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号