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类如下

燕雀Logo
燕雀Logo

为用户提供LOGO免费设计在线生成服务

下载
  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

 

 

  

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

175

2026.01.28

包子漫画在线官方入口大全
包子漫画在线官方入口大全

本合集汇总了包子漫画2026最新官方在线观看入口,涵盖备用域名、正版无广告链接及多端适配地址,助你畅享12700+高清漫画资源。阅读专题下面的文章了解更多详细内容。

35

2026.01.28

ao3中文版官网地址大全
ao3中文版官网地址大全

AO3最新中文版官网入口合集,汇总2026年主站及国内优化镜像链接,支持简体中文界面、无广告阅读与多设备同步。阅读专题下面的文章了解更多详细内容。

79

2026.01.28

php怎么写接口教程
php怎么写接口教程

本合集涵盖PHP接口开发基础、RESTful API设计、数据交互与安全处理等实用教程,助你快速掌握PHP接口编写技巧。阅读专题下面的文章了解更多详细内容。

2

2026.01.28

php中文乱码如何解决
php中文乱码如何解决

本文整理了php中文乱码如何解决及解决方法,阅读节专题下面的文章了解更多详细内容。

4

2026.01.28

Java 消息队列与异步架构实战
Java 消息队列与异步架构实战

本专题系统讲解 Java 在消息队列与异步系统架构中的核心应用,涵盖消息队列基本原理、Kafka 与 RabbitMQ 的使用场景对比、生产者与消费者模型、消息可靠性与顺序性保障、重复消费与幂等处理,以及在高并发系统中的异步解耦设计。通过实战案例,帮助学习者掌握 使用 Java 构建高吞吐、高可靠异步消息系统的完整思路。

8

2026.01.28

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

24

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

122

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

72

2026.01.26

热门下载

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

精品课程

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

共18课时 | 4.9万人学习

Git 教程
Git 教程

共21课时 | 3.1万人学习

Django 教程
Django 教程

共28课时 | 3.6万人学习

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

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