SAX 解析到文件,缓存到内存

2024-04-01 21:58
文章标签 内存 解析 缓存 sax

本文主要是介绍SAX 解析到文件,缓存到内存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目的
    通过一个小的SAX例子,我们更清晰的理解SAX的工作原理。

    本文例子主要实现:
    1. 将每个Employee信息输出到自己的文件中,文件名是以Employee ID和Employee Name来命名的,注意,观察代码中是如何得到Employee ID和Employee Name;
    2. 将每个Employee信息存入到Map中,其中,Map中的每个Value对应一个Employee的Collection,Map中的每个Key对应该Employee的ID。


    package shuai.study.sax.demo;  import java.io.File;  import java.io.IOException;  import java.util.Collection;  import java.util.HashMap;  import java.util.LinkedList;  import java.util.Map;  import javax.xml.parsers.ParserConfigurationException;  import javax.xml.parsers.SAXParser;  import javax.xml.parsers.SAXParserFactory;  import org.apache.commons.io.FileUtils;  import org.apache.commons.lang3.StringUtils;  import org.xml.sax.Attributes;  import org.xml.sax.SAXException;  import org.xml.sax.helpers.DefaultHandler;  /** * @author shengshu *  */  public class SaxHandler extends DefaultHandler {  private final static String leafNodeText = "|firstname|;|lastname|;|sex|;|country|;|province|;|city|;|village|;|mobile|;|mail|;|qq|;|postcode|;|profession|";  private Map<String, Collection<String>> companyMap = null;  private Collection<String> employeeCollection = null;  private String currentValue = null;  private String currentCharacters = null;  private StringBuffer idAndNameStringBuffer = null;  public SaxHandler(File inputFile) {  this.parseDocument(inputFile);  }  private void parseDocument(File inputFile) {  SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();  try {  SAXParser saxParser = saxParserFactory.newSAXParser();  saxParser.parse(inputFile, this);  } catch (ParserConfigurationException pce) {  pce.printStackTrace();  } catch (SAXException saxe) {  saxe.printStackTrace();  } catch (IOException ioe) {  ioe.printStackTrace();  }  }  @Override  public void startDocument() throws SAXException {  super.startDocument();  this.companyMap = new HashMap<String, Collection<String>>();  }  @Override  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  if (qName.equalsIgnoreCase("Employee")) {  this.employeeCollection = new LinkedList<String>();  this.idAndNameStringBuffer = new StringBuffer();  this.currentValue = attributes.getValue("ID");  }  }  @Override  public void characters(char[] buffer, int start, int length) {  this.currentCharacters = new String(buffer, start, length);  }  @Override  public void endElement(String uri, String localName, String qName) throws SAXException {  if (StringUtils.containsIgnoreCase(leafNodeText, "|" + qName + "|")) {  this.employeeCollection.add(qName + ": " + this.currentCharacters);  if (qName.equalsIgnoreCase("FirstName")) {  this.idAndNameStringBuffer.append(this.currentCharacters);  }  if (qName.equalsIgnoreCase("LastName")) {  this.idAndNameStringBuffer.append(this.currentCharacters);  }  }  if (qName.equalsIgnoreCase("Employee")) {  this.companyMap.put(this.currentValue, this.employeeCollection);  this.idAndNameStringBuffer.append("-").append(this.currentValue);  this.writeEmployee(employeeCollection, idAndNameStringBuffer.toString());  }  }  private void writeEmployee(Collection<String> employeeCollection, String fileName) {  String outputFileDirectory = SaxHandler.class.getResource("/file/output/").getPath();  String outputFilePath = outputFileDirectory + fileName + ".xml";  File outputFile = new File(outputFilePath);  try {  FileUtils.writeLines(outputFile, employeeCollection, false);  } catch (IOException ioe) {  ioe.printStackTrace();  }  }  @Override  public void endDocument() throws SAXException {  super.endDocument();  }  public Map<String, Collection<String>> getCompanyMap() {  return this.companyMap;  }  }  

    package shuai.study.sax.demo;  import java.io.File;  import java.util.Collection;  import java.util.Iterator;  import java.util.Map;  import java.util.Map.Entry;  /** * @author shengshu *  */  public class SaxDemo {  public static void displayCompany(Map<String, Collection<String>> companyMap) {  Iterator<Entry<String, Collection<String>>> companyIterator = companyMap.entrySet().iterator();  while (companyIterator.hasNext()) {  Entry<String, Collection<String>> companyEntry = companyIterator.next();  String id = companyEntry.getKey();  System.out.println("============== Employee ID " + id + " Start ==============");  Collection<String> employeeCollection = companyEntry.getValue();  Iterator<String> employeeIterator = employeeCollection.iterator();  while (employeeIterator.hasNext()) {  String leafNodeAndValue = employeeIterator.next();  System.out.println(leafNodeAndValue);  }  System.out.println("============== Employee ID " + id + " End ==============");  }  }  public static void main(String[] args) {  String inputFilePath = SaxDemo.class.getResource("/file/input/company.xml").getPath();  File inputFile = new File(inputFilePath);  SaxHandler saxHandler = new SaxHandler(inputFile);  Map<String, Collection<String>> companyMap = saxHandler.getCompanyMap();  SaxDemo.displayCompany(companyMap);  }  }  

    <?xml version = "1.0" encoding="UTF-8"?>  <Company>  <Employee ID="37">  <Name>  <FirstName>Zhou</FirstName>  <LastName>Shengshuai</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>ShanDong</Province>  <City>LinYi</City>  <Village>FengHuangYu</Village>  <Contact>  <Mobile>18108***778</Mobile>  <Mail>zhoushengshuai2007@163.com</Mail>  <QQ>254392398</QQ>  <Postcode>276422</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  <Employee ID="66">  <Name>  <FirstName>Wang</FirstName>  <LastName>Eric</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>HeBei</Province>  <City>QinHuangDao</City>  <Village>hhh</Village>  <Contact>  <Mobile>150*****955</Mobile>  <Mail>eric@163.com</Mail>  <QQ>666666666</QQ>  <Postcode>111666</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  <Employee ID="99">  <Name>  <FirstName>Shi</FirstName>  <LastName>Stone</LastName>  </Name>  <Sex>Male</Sex>  <Address>  <Country>China</Country>  <Province>HeNan</Province>  <City>PingDingShan</City>  <Village>nnn</Village>  <Contact>  <Mobile>186*****015</Mobile>  <Mail>stone@163.com</Mail>  <QQ>999999999</QQ>  <Postcode>111999</Postcode>  </Contact>  </Address>  <Profession>Software</Profession>  </Employee>  </Company>  

这篇关于SAX 解析到文件,缓存到内存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/868234

相关文章

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

全面解析MySQL索引长度限制问题与解决方案

《全面解析MySQL索引长度限制问题与解决方案》MySQL对索引长度设限是为了保持高效的数据检索性能,这个限制不是MySQL的缺陷,而是数据库设计中的权衡结果,下面我们就来看看如何解决这一问题吧... 目录引言:为什么会有索引键长度问题?一、问题根源深度解析mysql索引长度限制原理实际场景示例二、五大解决

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实