关键词搜索

源码搜索 ×
×

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

发布2019-08-24浏览1187次

详情内容

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

  • *.xml
  • *.proerties

XML解析方式

目录

JavaPath 获取

Java解析XML的三种方式

SAX

DOM

DOM4j


JavaPath 获取

  1. package com.boonya.path;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.Properties;
  5. import javax.servlet.ServletContext;
  6. import javax.servlet.http.HttpServletRequest;
  7. /**
  8. * Java 中配置文件的读取方式
  9. * @packge com.boonya.path.JavaPath
  10. * @date 2019年8月23日 下午10:42:48
  11. * @author pengjunlin
  12. * @comment
  13. * @update
  14. */
  15. public class JavaPath {
  16. /**
  17. * 读取与类同级的properties文件
  18. * @MethodName: getPropertiesIn
  19. * @Description:
  20. * @param clazz
  21. * @param propertiesPath
  22. * @return
  23. * @throws IOException
  24. * @throws
  25. */
  26. @SuppressWarnings("rawtypes")
  27. public static Properties getProperties(Class clazz,String propertiesPath) throws IOException{
  28. InputStream is= clazz.getResourceAsStream(propertiesPath);
  29. Properties p=new Properties();
  30. p.load(is);
  31. return p;
  32. }
  33. /**
  34. * 读取资源与类同级的properties文件
  35. * @MethodName: getPropertiesIn
  36. * @Description:
  37. * @param clazz
  38. * @param propertiesPath
  39. * @return
  40. * @throws IOException
  41. * @throws
  42. */
  43. public static Properties getResourceProperties(String propertiesPath) throws IOException{
  44. InputStream is= JavaPath.class.getResourceAsStream("/"+propertiesPath);
  45. Properties p=new Properties();
  46. p.load(is);
  47. return p;
  48. }
  49. /**
  50. * 读取WEB-INF路径下的properties文件
  51. * @MethodName: getProperties
  52. * @Description:
  53. * @param request
  54. * @param webInfPropertiesPath
  55. * @return
  56. * @throws IOException
  57. * @throws
  58. */
  59. public static Properties getProperties(HttpServletRequest request,String webInfPropertiesPath) throws IOException{
  60. ServletContext context=request.getSession().getServletContext();
  61. InputStream is=context.getResourceAsStream(webInfPropertiesPath);
  62. Properties p=new Properties();
  63. p.load(is);
  64. return p;
  65. }
  66. public static void main(String[] args) throws IOException {
  67. Properties pro=JavaPath.getResourceProperties("Test.properties");
  68. System.out.println(pro.getProperty("server"));
  69. System.out.println(pro.getProperty("port"));
  70. }
  71. }

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

Java解析XML的三种方式

SAX

  1. package com.boonya.xml;
  2. import org.xml.sax.Attributes;
  3. import org.xml.sax.SAXException;
  4. import org.xml.sax.helpers.DefaultHandler;
  5. //
  6. public class Saxhandler extends DefaultHandler {
  7. @Override
  8. public void startDocument() throws SAXException {
  9. System.out.println("开始解析XML文档...");
  10. }
  11. @Override
  12. public void endDocument() throws SAXException {
  13. System.out.println("结束解析XML文档...");
  14. }
  15. @Override
  16. public void startElement(String uri, String localName, String qName,
  17. Attributes attributes) throws SAXException {
  18. // TODO Auto-generated method stub
  19. super.startElement(uri, localName, qName, attributes);
  20. System.out.println("开始解析节点["+qName+"]...");
  21. System.out.println("共有["+attributes.getLength()+"]个属性");
  22. }
  23. @Override
  24. public void characters(char[] ch, int start, int length)
  25. throws SAXException {
  26. // TODO Auto-generated method stub
  27. super.characters(ch, start, length);
  28. String content =new String(ch,start,length);
  29. System.out.println(content);
  30. }
  31. @Override
  32. public void endElement(String uri, String localName, String qName)
  33. throws SAXException {
  34. // TODO Auto-generated method stub
  35. super.endElement(uri, localName, qName);
  36. System.out.println("结束解析XML节点...");
  37. }
  38. }

DOM

  1. package com.boonya.xml;
  2. import java.util.Iterator;
  3. import javax.xml.parsers.DocumentBuilder;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import org.w3c.dom.Document;
  6. import org.w3c.dom.Element;
  7. import org.w3c.dom.NamedNodeMap;
  8. import org.w3c.dom.Node;
  9. import org.w3c.dom.NodeList;
  10. public class DomHandler {
  11. /*
  12. * 解析XML
  13. */
  14. public void read(String fileName) throws Exception {
  15. // 定义工厂API 使应用程序能够从XML文档获取生成DOM对象树的解析器
  16. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  17. // 获取此类的实例之后,将可以从各种输入源解析XML
  18. DocumentBuilder builder = factory.newDocumentBuilder();
  19. // builder.parse(this.getClass().getResourceAsStream("/" + fileName));
  20. // Document接口表示整个HTML或XML文档,从概念上讲,它是文档树的根,并提供对文档数据的基本访问
  21. Document document = builder.parse(this.getClass().getResourceAsStream(
  22. "/" + fileName));
  23. // 获取根节点
  24. Element root = document.getDocumentElement();
  25. System.out.println(root.getNodeName());
  26. //读取database节点NodeList接口提供对节点的有序集合的抽象
  27. NodeList nodeList = root.getElementsByTagName("database");
  28. for (int i = 0; i < nodeList.getLength(); i++) {
  29. // 获取一个节点
  30. Node node = nodeList.item(i);
  31. // 获取该节点所有属性
  32. NamedNodeMap attributes = node.getAttributes();
  33. for (int j = 0; j < attributes.getLength(); j++) {
  34. Node attribute = attributes.item(j);
  35. System.out.println(attribute.getNodeName() + ":"
  36. + attribute.getNodeValue());
  37. }
  38. //获取所有子节点数据
  39. NodeList childNodes=node.getChildNodes();
  40. for (int j = 0; j < childNodes.getLength(); j++) {
  41. Node childNode=childNodes.item(j);
  42. System.out.println(childNode.getNodeName()+":"+childNode.getNodeValue());
  43. }
  44. }
  45. }
  46. public static void main(String[] args) throws Exception {
  47. new DomHandler().read("data-source.xml");
  48. }
  49. }

DOM4j

  1. package com.boonya.xml;
  2. import java.io.FileOutputStream;
  3. import java.sql.DatabaseMetaData;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import org.dom4j.*;
  7. import org.dom4j.io.OutputFormat;
  8. import org.dom4j.io.SAXReader;
  9. import org.dom4j.io.XMLWriter;
  10. public class Dom4jHandler {
  11. public void add() throws Exception {
  12. // 1.创建一个Document
  13. Document document = DocumentHelper.createDocument();
  14. // 2.给Document添加数据
  15. Element root = document.addElement("DataSource");
  16. // 添加注释
  17. root.addComment("这是注释信息");
  18. // 在root根节点下面添加一个子节点
  19. Element database = root.addElement("database");
  20. database.addAttribute("name", "mysql");
  21. database.addAttribute("version", "5.0");
  22. // 添加子节点
  23. database.addElement("driver").setText("com.mysql.jdbc.Driver");
  24. database.addElement("url")
  25. .setText("jdbc:mysql://localhost:3306/myjdbc");
  26. database.addElement("user").setText("root");
  27. database.addElement("password").setText("root");
  28. // 3.将Document写出文件
  29. OutputFormat format = OutputFormat.createPrettyPrint();
  30. format.setEncoding("utf-8");
  31. // FileOutputStream默认生成的路径在根路径
  32. XMLWriter xw = new XMLWriter(new FileOutputStream("db.xml"), format);
  33. xw.write(document);
  34. xw.close();
  35. }
  36. public void update(String fileName) throws Exception {
  37. // sax解析器
  38. SAXReader saxReader = new SAXReader();
  39. // 读到对象
  40. Document document = saxReader.read(this.getClass().getResourceAsStream(
  41. "/" + fileName));
  42. Element root = document.getRootElement();
  43. List<Element> databases_node = root.elements("database");
  44. for (Element database_node : databases_node) {
  45. if (database_node.attributeValue("name").equalsIgnoreCase("mysql")) {
  46. System.out.println("old:"
  47. + database_node.attributeValue("name"));
  48. database_node.attribute("name").setText("Oracle");
  49. System.out.println("update:"
  50. + database_node.attributeValue("name"));
  51. database_node.element("driver").setText("oracel");
  52. database_node.element("url").setText("jdbc");
  53. // 删除password节点
  54. database_node.remove(database_node.element("password"));
  55. // 删除属性
  56. database_node.remove(database_node.attribute("version"));
  57. }
  58. }
  59. OutputFormat format = OutputFormat.createPrettyPrint();
  60. format.setEncoding("utf-8");
  61. // FileOutputStream默认生成的路径在根路径
  62. XMLWriter xw = new XMLWriter(new FileOutputStream("db2.xml"), format);
  63. xw.write(document);
  64. xw.close();
  65. }
  66. public void read(String fileName) throws Exception {
  67. // sax解析器
  68. SAXReader saxReader = new SAXReader();
  69. // 读到对象
  70. Document document = saxReader.read(this.getClass().getResourceAsStream(
  71. "/" + fileName));
  72. Element root = document.getRootElement();
  73. System.out.println("根节点:" + root.getName());
  74. // List<Element> childElements=root.elements();
  75. List<Element> childElements = root.elements("database");
  76. for (Element child : childElements) {
  77. // 获取属性 不知道属性名称时的遍历方法
  78. List<Attribute> attributes = child.attributes();
  79. // for (Attribute attribute : attributes) {
  80. // System.out.println(attribute.getName()+":"+attribute.getValue());
  81. // }
  82. String name = child.attributeValue("name");
  83. // String version = child.attributeValue("version");
  84. String version = child.attribute("version").getValue();
  85. System.out.println(name + ":" + version);
  86. // //获取子节点
  87. // List<Element> childs=child.elements();
  88. // for (Element element : childs) {
  89. // System.out.println(element.getName()+":"+element.getText());
  90. // }
  91. System.out.println(child.elementText("driver"));
  92. System.out.println(child.element("url").getText());
  93. System.out.println(child.elementTextTrim("user"));
  94. System.out.println(child.element("password").getTextTrim());
  95. }
  96. }
  97. public static void main(String[] args) throws Exception {
  98. // new Dom4jHandler().read("data-source.xml");
  99. // new Dom4jHandler().add();
  100. new Dom4jHandler().update("data-source.xml");
  101. }
  102. }

Dom4j获取文档:

  1. package com.boonya.xml;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.net.URL;
  5. import org.dom4j.Document;
  6. import org.dom4j.DocumentException;
  7. import org.dom4j.io.SAXReader;
  8. public class Dom4jXMLParser {
  9. /**
  10. * 获得XML文档对象(InputStream is = Dom4jXMLParser.class.getResourceAsStream("/Test.xml");)
  11. * @MethodName: getDocument
  12. * @Description:
  13. * @param is
  14. * @return
  15. * @throws
  16. */
  17. public static Document getDocument(InputStream is) {
  18. Document document=null;
  19. try {
  20. SAXReader saxReader = new SAXReader();
  21. document = saxReader.read(is);
  22. } catch (DocumentException e) {
  23. e.printStackTrace();
  24. }
  25. return document;
  26. }
  27. /**
  28. * 获得XML文档对象
  29. * @MethodName: getDocument
  30. * @Description:
  31. * @param filePath
  32. * @return
  33. * @throws
  34. */
  35. public static Document getDocument(String filePath) {
  36. Document document = null;
  37. try {
  38. SAXReader saxReader = new SAXReader();
  39. document = saxReader.read(new File(filePath));
  40. } catch (Exception ex) {
  41. ex.printStackTrace();
  42. }
  43. return document;
  44. }
  45. /**
  46. * 获得网络XML文档对象
  47. * @MethodName: getDocument
  48. * @Description:
  49. * @param url
  50. * @return
  51. * @throws
  52. */
  53. public static Document getDocument(URL url) {
  54. Document document = null;
  55. try {
  56. SAXReader saxReader = new SAXReader();
  57. document = saxReader.read(url);
  58. } catch (Exception ex) {
  59. ex.printStackTrace();
  60. }
  61. return document;
  62. }
  63. public static void main(String[] args) throws DocumentException {
  64. }
  65. }

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

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载