java读取xml配置文件和properties配置文件

本文介绍了如何使用Dom4j库解析XML文件,并通过Java代码示例展示了具体的实现方法。此外,还提供了从Properties文件中读取配置信息的方法。

1.读取xml

使用dom4j解析xml  下载地址:http://sourceforge.net/projects/dom4j/files/

 
  
  1. import org.dom4j.Document;  
  2. import org.dom4j.Element; 
  3. import org.dom4j.io.SAXReader;

try
{ File f = new File(filename); if (!f.exists()) { System.out.println(" Error : Config file doesn't exist!"); System.exit(1); } SAXReader reader = new SAXReader(); Document doc; doc = reader.read(f); Element root = doc.getRootElement(); Element data; Iterator<?> itr = root.elementIterator("VALUE"); data = (Element) itr.next(); config.server = data.elementText("server").trim(); config.user = data.elementText("user").trim(); config.pass = data.elementText("pass").trim(); config.port = data.elementText("port").trim(); config.dbname = data.elementText("dbname").trim(); } catch (Exception ex) { System.out.println("Error : " + ex.toString()); }

 

测试xml

<?xml version="1.0" encoding="UTF-8"?>  
<CONFIG>  
    <VALUE>  
        <!-- mysql连接设置 -->  
        <server>127.0.0.1</server>  
        <dbname>users</dbname>  
        <user>root</user>  
        <pass>pass</pass>  
        <port>3306</port>  
    </VALUE>  
</CONFIG> 

2.读取properties

Properties prop = new Properties();
//        ClassLoader classLoader = this.getClass().getClassLoader();
//        InputStream is = classLoader.getResourceAsStream("/healthfile.properties");
        //spring中
ServletContext context = this.getServletContext(); InputStream is = context.getResourceAsStream("/WEB-INF/classes/healthfile.properties");
//javase
//InputStream is = this.getClass().getResourceAsStream("/resource/sqlAddress.properties"); prop.load(is); is.close(); String implClass
= prop.getProperty("impl.class"); String statichtmlLocalRootPath = prop.getProperty("statichtml.local.rootPath");

 

转载于:https://www.cnblogs.com/mengxiangqihang/p/4150450.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值