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

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

时间:2014-12-08 10:40:30      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

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");
        ServletContext context = this.getServletContext();
        InputStream is = context.getResourceAsStream("/WEB-INF/classes/healthfile.properties");
        prop.load(is);
        is.close();
        String implClass = prop.getProperty("impl.class");
        String statichtmlLocalRootPath = prop.getProperty("statichtml.local.rootPath");

 

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

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/mengxiangqihang/p/4150450.html

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