天下之事,必先处之难,而后易之。

Java获取配置文件路径方式与XML解析

Java中最常用的配置文件格式:

  • *.xml
  • *.proerties

XML解析方式

目录

JavaPath 获取

Java解析XML的三种方式

SAX

DOM

DOM4j


JavaPath 获取

package com.boonya.path;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
/**
 * Java 中配置文件的读取方式
 * @packge com.boonya.path.JavaPath
 * @date   2019年8月23日  下午10:42:48
 * @author pengjunlin
 * @comment   
 * @update
 */
public class JavaPath {
	
	/**
	 * 读取与类同级的properties文件
	 * @MethodName: getPropertiesIn 
	 * @Description: 
	 * @param clazz
	 * @param propertiesPath
	 * @return
	 * @throws IOException
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public static Properties getProperties(Class clazz,String propertiesPath) throws IOException{
		InputStream is= clazz.getResourceAsStream(propertiesPath);
		Properties p=new Properties();
		p.load(is);
		return p;
	}
	
	/**
	 * 读取资源与类同级的properties文件
	 * @MethodName: getPropertiesIn 
	 * @Description: 
	 * @param clazz
	 * @param propertiesPath
	 * @return
	 * @throws IOException
	 * @throws
	 */
	public static Properties getResourceProperties(String propertiesPath) throws IOException{
		InputStream is= JavaPath.class.getResourceAsStream("/"+propertiesPath);
		Properties p=new Properties();
		p.load(is);
		return p;
	}
	
	/**
	 * 读取WEB-INF路径下的properties文件
	 * @MethodName: getProperties 
	 * @Description: 
	 * @param request
	 * @param webInfPropertiesPath
	 * @return
	 * @throws IOException
	 * @throws
	 */
	public static Properties getProperties(HttpServletRequest request,String webInfPropertiesPath) throws IOException{
		ServletContext context=request.getSession().getServletContext();
		InputStream is=context.getResourceAsStream(webInfPropertiesPath);
		Properties p=new Properties();
		p.load(is);
		return p;
	}
	
	public static void main(String[] args) throws IOException {
		Properties pro=JavaPath.getResourceProperties("Test.properties");
		System.out.println(pro.getProperty("server"));
		System.out.println(pro.getProperty("port"));
	}

}

参考地址:https://www.cnblogs.com/omji0030/p/11000040.html

Java解析XML的三种方式

SAX

package com.boonya.xml;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
//
public class Saxhandler extends DefaultHandler {
 
    @Override
    public void startDocument() throws SAXException {
        System.out.println("开始解析XML文档...");
    }
 
    @Override
    public void endDocument() throws SAXException {
        System.out.println("结束解析XML文档...");
    }
 
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        System.out.println("开始解析节点["+qName+"]...");
        System.out.println("共有["+attributes.getLength()+"]个属性");
    }
 
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, length);
        String content =new String(ch,start,length);
        System.out.println(content);
    }
 
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        super.endElement(uri, localName, qName);
        System.out.println("结束解析XML节点...");
    }
}

DOM

package com.boonya.xml;
 
import java.util.Iterator;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class DomHandler {
 
    /*
     * 解析XML
     */
    public void read(String fileName) throws Exception {
        // 定义工厂API 使应用程序能够从XML文档获取生成DOM对象树的解析器
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 获取此类的实例之后,将可以从各种输入源解析XML
        DocumentBuilder builder = factory.newDocumentBuilder();
        // builder.parse(this.getClass().getResourceAsStream("/" + fileName));
        // Document接口表示整个HTML或XML文档,从概念上讲,它是文档树的根,并提供对文档数据的基本访问
        Document document = builder.parse(this.getClass().getResourceAsStream(
                "/" + fileName));
        // 获取根节点
        Element root = document.getDocumentElement();
        System.out.println(root.getNodeName());
 
        //读取database节点NodeList接口提供对节点的有序集合的抽象
        NodeList nodeList = root.getElementsByTagName("database");
        for (int i = 0; i < nodeList.getLength(); i++) {
            // 获取一个节点
            Node node = nodeList.item(i);
            // 获取该节点所有属性
            NamedNodeMap attributes = node.getAttributes();
            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                System.out.println(attribute.getNodeName() + ":"
                        + attribute.getNodeValue());
            }
            //获取所有子节点数据
            NodeList childNodes=node.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node childNode=childNodes.item(j);
                System.out.println(childNode.getNodeName()+":"+childNode.getNodeValue());
            }
        }
    }
 
    public static void main(String[] args) throws Exception {
        new DomHandler().read("data-source.xml");
 
    }
}

DOM4j

package com.boonya.xml;

import java.io.FileOutputStream;
import java.sql.DatabaseMetaData;
import java.util.Iterator;
import java.util.List;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jHandler {

	public void add() throws Exception {
		// 1.创建一个Document
		Document document = DocumentHelper.createDocument();
		// 2.给Document添加数据
		Element root = document.addElement("DataSource");
		// 添加注释
		root.addComment("这是注释信息");
		// 在root根节点下面添加一个子节点
		Element database = root.addElement("database");
		database.addAttribute("name", "mysql");
		database.addAttribute("version", "5.0");
		// 添加子节点
		database.addElement("driver").setText("com.mysql.jdbc.Driver");
		database.addElement("url")
				.setText("jdbc:mysql://localhost:3306/myjdbc");
		database.addElement("user").setText("root");
		database.addElement("password").setText("root");
		// 3.将Document写出文件
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		// FileOutputStream默认生成的路径在根路径
		XMLWriter xw = new XMLWriter(new FileOutputStream("db.xml"), format);
		xw.write(document);
		xw.close();
	}

	public void update(String fileName) throws Exception {
		// sax解析器
		SAXReader saxReader = new SAXReader();
		// 读到对象
		Document document = saxReader.read(this.getClass().getResourceAsStream(
				"/" + fileName));
		Element root = document.getRootElement();
		List<Element> databases_node = root.elements("database");
		for (Element database_node : databases_node) {
			if (database_node.attributeValue("name").equalsIgnoreCase("mysql")) {
				System.out.println("old:"
						+ database_node.attributeValue("name"));
				database_node.attribute("name").setText("Oracle");
				System.out.println("update:"
						+ database_node.attributeValue("name"));

				database_node.element("driver").setText("oracel");
				database_node.element("url").setText("jdbc");

				// 删除password节点
				database_node.remove(database_node.element("password"));

				// 删除属性
				database_node.remove(database_node.attribute("version"));
			}
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		// FileOutputStream默认生成的路径在根路径
		XMLWriter xw = new XMLWriter(new FileOutputStream("db2.xml"), format);
		xw.write(document);
		xw.close();
	}

	public void read(String fileName) throws Exception {
		// sax解析器
		SAXReader saxReader = new SAXReader();
		// 读到对象
		Document document = saxReader.read(this.getClass().getResourceAsStream(
				"/" + fileName));
		Element root = document.getRootElement();
		System.out.println("根节点:" + root.getName());

		// List<Element> childElements=root.elements();
		List<Element> childElements = root.elements("database");
		for (Element child : childElements) {
			// 获取属性 不知道属性名称时的遍历方法
			List<Attribute> attributes = child.attributes();
			// for (Attribute attribute : attributes) {
			// System.out.println(attribute.getName()+":"+attribute.getValue());
			// }
			String name = child.attributeValue("name");
			// String version = child.attributeValue("version");
			String version = child.attribute("version").getValue();
			System.out.println(name + ":" + version);

			// //获取子节点
			// List<Element> childs=child.elements();
			// for (Element element : childs) {
			// System.out.println(element.getName()+":"+element.getText());
			// }
			System.out.println(child.elementText("driver"));
			System.out.println(child.element("url").getText());
			System.out.println(child.elementTextTrim("user"));
			System.out.println(child.element("password").getTextTrim());

		}
	}

	public static void main(String[] args) throws Exception {
		// new Dom4jHandler().read("data-source.xml");
		// new Dom4jHandler().add();
		new Dom4jHandler().update("data-source.xml");
	}
}

Dom4j获取文档:

package com.boonya.xml;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Dom4jXMLParser {
	
	/**
	 * 获得XML文档对象(InputStream is = Dom4jXMLParser.class.getResourceAsStream("/Test.xml");)
	 * @MethodName: getDocument 
	 * @Description: 
	 * @param is
	 * @return
	 * @throws
	 */
	public static Document getDocument(InputStream is) {  
		Document document=null;
		try {
			SAXReader saxReader = new SAXReader();
			document = saxReader.read(is);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	    return document;  
	}
	
	/**
	 * 获得XML文档对象
	 * @MethodName: getDocument 
	 * @Description: 
	 * @param filePath
	 * @return
	 * @throws
	 */
	public static Document getDocument(String filePath) {  
	    Document document = null;  
	    try {  
	        SAXReader saxReader = new SAXReader();  
	        document = saxReader.read(new File(filePath)); 
	    } catch (Exception ex) {  
	        ex.printStackTrace();  
	    }  
	    return document;  
	}  
	
	/**
	 * 获得网络XML文档对象
	 * @MethodName: getDocument 
	 * @Description: 
	 * @param url
	 * @return
	 * @throws
	 */
	public static Document getDocument(URL url) {  
	    Document document = null;  
	    try {  
	        SAXReader saxReader = new SAXReader();  
	        document = saxReader.read(url);
	    } catch (Exception ex) {  
	        ex.printStackTrace();  
	    }  
	    return document;  
	}  

	public static void main(String[] args) throws DocumentException {
		
	}

}

Dom4j完整教程:https://blog.csdn.net/chenweitang123/article/details/6255108

 

posted @ 2023-12-11 18:54  boonya  阅读(20)  评论(0)    收藏  举报  来源
我有佳人隔窗而居,今有伊人明月之畔。
轻歌柔情冰壶之浣,涓涓清流梦入云端。
美人如娇温雅悠婉,目遇赏阅适而自欣。
百草层叠疏而有致,此情此思怀彼佳人。
念所思之唯心叩之,踽踽彳亍寤寐思之。
行云如风逝而复归,佳人一去莫知可回?
深闺冷瘦独自徘徊,处处明灯影还如只。
推窗见月疑是归人,阑珊灯火托手思忖。
庐居闲客而好品茗,斟茶徐徐漫漫生烟。

我有佳人在水之畔,瓮载渔舟浣纱归还。
明月相照月色还低,浅近芦苇深深如钿。
庐山秋月如美人衣,画堂春阁香气靡靡。
秋意幽笃残粉摇曳,轻轻如诉画中蝴蝶。
泾水潺潺取尔浇园,暮色黄昏如沐佳人。
青丝撩弄长裙翩翩,彩蝶飞舞执子手腕。
香带丝缕缓缓在肩,柔美体肤寸寸爱怜。
如水之殇美玉成欢,我有佳人清新如兰。
伊人在水我在一边,远远相望不可亵玩。