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

时间:2022-08-30 11:23:26

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()); }

 

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

测试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");