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

简介: 目的<br>     通过一个小的SAX例子,我们更清晰的理解SAX的工作原理。<br><br>     本文例子主要实现:<br>     1. 将每个Employee信息输出到自己的文件中,文件名是以Employee ID和Employee Name来命名的,注意,观察代码中是如何得到Employee ID和Employee Name;<br>     2. 将每个Employ
目的
    通过一个小的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>  

相关文章
|
7月前
|
Web App开发 缓存 监控
内存溢出与内存泄漏:解析与解决方案
本文深入解析内存溢出与内存泄漏的区别及成因,结合Java代码示例展示典型问题场景,剖析静态集合滥用、资源未释放等常见原因,并提供使用分析工具、优化内存配置、分批处理数据等实用解决方案,助力提升程序稳定性与性能。
1924 1
|
12月前
|
Arthas 存储 算法
深入理解JVM,包含字节码文件,内存结构,垃圾回收,类的声明周期,类加载器
JVM全称是Java Virtual Machine-Java虚拟机JVM作用:本质上是一个运行在计算机上的程序,职责是运行Java字节码文件,编译为机器码交由计算机运行类的生命周期概述:类的生命周期描述了一个类加载,使用,卸载的整个过类的生命周期阶段:类的声明周期主要分为五个阶段:加载->连接->初始化->使用->卸载,其中连接中分为三个小阶段验证->准备->解析类加载器的定义:JVM提供类加载器给Java程序去获取类和接口字节码数据类加载器的作用:类加载器接受字节码文件。
982 55
|
7月前
|
弹性计算 定位技术 数据中心
阿里云服务器配置选择方法:付费类型、地域及CPU内存配置全解析
阿里云服务器怎么选?2025最新指南:就近选择地域,降低延迟;长期使用选包年包月,短期灵活选按量付费;企业选2核4G5M仅199元/年,个人选2核2G3M低至99元/年,高性价比爆款推荐,轻松上云。
828 11
|
8月前
|
存储 大数据 Unix
Python生成器 vs 迭代器:从内存到代码的深度解析
在Python中,处理大数据或无限序列时,迭代器与生成器可避免内存溢出。迭代器通过`__iter__`和`__next__`手动实现,控制灵活;生成器用`yield`自动实现,代码简洁、内存高效。生成器适合大文件读取、惰性计算等场景,是性能优化的关键工具。
410 2
|
9月前
|
弹性计算 前端开发 NoSQL
2025最新阿里云服务器配置选择攻略:CPU、内存、带宽与系统盘全解析
本文详解2025年阿里云服务器ECS配置选择策略,涵盖CPU、内存、带宽与系统盘推荐,助你根据业务需求精准选型,提升性能与性价比。
|
9月前
|
缓存 监控 安全
告别缓存击穿!Go 语言中的防并发神器:singleflight 包深度解析
在高并发场景中,多个请求同时访问同一资源易导致缓存击穿、数据库压力过大。Go 语言提供的 `singleflight` 包可将相同 key 的请求合并,仅执行一次实际操作,其余请求共享结果,有效降低系统负载。本文详解其原理、实现及典型应用场景,并附示例代码,助你掌握高并发优化技巧。
680 0
|
10月前
|
存储 弹性计算 固态存储
阿里云服务器配置费用整理,支持一万人CPU内存、公网带宽和存储IO性能全解析
要支撑1万人在线流量,需选择阿里云企业级ECS服务器,如通用型g系列、高主频型hf系列或通用算力型u1实例,配置如16核64G及以上,搭配高带宽与SSD/ESSD云盘,费用约数千元每月。
1305 0
|
11月前
|
存储 缓存 数据挖掘
阿里云服务器实例选购指南:经济型、通用算力型、计算型、通用型、内存型性能与适用场景解析
当我们在通过阿里云的活动页面挑选云服务器时,相同配置的云服务器通常会有多种不同的实例供我们选择,并且它们之间的价格差异较为明显。这是因为不同实例规格所采用的处理器存在差异,其底层架构也各不相同,比如常见的X86计算架构和Arm计算架构。正因如此,不同实例的云服务器在性能表现以及适用场景方面都各有特点。为了帮助大家在众多实例中做出更合适的选择,本文将针对阿里云服务器的经济型、通用算力型、计算型、通用型和内存型实例,介绍它们的性能特性以及对应的使用场景,以供大家参考和选择。
|
缓存 NoSQL Go
【LeetCode 热题100】146:LRU 缓存(详细解析)(Go语言版)
本文详细解析了力扣 146 题——LRU 缓存机制的实现方法。通过结合哈希表与双向链表,确保 `get` 和 `put` 操作均在 O(1) 时间内完成。哈希表用于快速查找,双向链表记录访问顺序,支持最近使用数据的高效更新与淘汰。代码以 Go 语言实现,结构清晰,涵盖核心操作如节点移动、插入与删除。此题为面试高频考点,适用于数据缓存、页面置换等场景,掌握后可加深对缓存策略的理解。
650 4

热门文章

最新文章

推荐镜像

更多
  • DNS