首页 > 代码库 > java读取xml配置文件和properties配置文件
java读取xml配置文件和properties配置文件
1.读取xml
使用dom4j解析xml 下载地址:http://sourceforge.net/projects/dom4j/files/
- import org.dom4j.Document;
- import org.dom4j.Element;
- 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配置文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。