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代码示例展示典型问题场景,剖析静态集合滥用、资源未释放等常见原因,并提供使用分析工具、优化内存配置、分批处理数据等实用解决方案,助力提升程序稳定性与性能。
1978 1
|
7月前
|
弹性计算 定位技术 数据中心
阿里云服务器配置选择方法:付费类型、地域及CPU内存配置全解析
阿里云服务器怎么选?2025最新指南:就近选择地域,降低延迟;长期使用选包年包月,短期灵活选按量付费;企业选2核4G5M仅199元/年,个人选2核2G3M低至99元/年,高性价比爆款推荐,轻松上云。
886 11
|
8月前
|
存储 大数据 Unix
Python生成器 vs 迭代器:从内存到代码的深度解析
在Python中,处理大数据或无限序列时,迭代器与生成器可避免内存溢出。迭代器通过`__iter__`和`__next__`手动实现,控制灵活;生成器用`yield`自动实现,代码简洁、内存高效。生成器适合大文件读取、惰性计算等场景,是性能优化的关键工具。
422 2
|
9月前
|
弹性计算 前端开发 NoSQL
2025最新阿里云服务器配置选择攻略:CPU、内存、带宽与系统盘全解析
本文详解2025年阿里云服务器ECS配置选择策略,涵盖CPU、内存、带宽与系统盘推荐,助你根据业务需求精准选型,提升性能与性价比。
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
3815 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
10月前
|
存储 弹性计算 固态存储
阿里云服务器配置费用整理,支持一万人CPU内存、公网带宽和存储IO性能全解析
要支撑1万人在线流量,需选择阿里云企业级ECS服务器,如通用型g系列、高主频型hf系列或通用算力型u1实例,配置如16核64G及以上,搭配高带宽与SSD/ESSD云盘,费用约数千元每月。
1363 0
|
机器学习/深度学习 存储 缓存
LLM高效推理:KV缓存与分页注意力机制深度解析
随着大型语言模型(LLM)规模和复杂性的增长,高效推理变得至关重要。KV缓存和分页注意力是优化LLM推理的两项关键技术。KV缓存通过存储键值对减少重复计算,而分页注意力则通过将序列分割成小块来降低内存消耗,从而有效处理长序列。本文深入剖析这些技术的工作原理及其在仅解码器模型中的应用,探讨其优势与挑战,并展示其实现示例。
1145 16
LLM高效推理:KV缓存与分页注意力机制深度解析
|
11月前
|
存储 缓存 数据挖掘
阿里云服务器实例选购指南:经济型、通用算力型、计算型、通用型、内存型性能与适用场景解析
当我们在通过阿里云的活动页面挑选云服务器时,相同配置的云服务器通常会有多种不同的实例供我们选择,并且它们之间的价格差异较为明显。这是因为不同实例规格所采用的处理器存在差异,其底层架构也各不相同,比如常见的X86计算架构和Arm计算架构。正因如此,不同实例的云服务器在性能表现以及适用场景方面都各有特点。为了帮助大家在众多实例中做出更合适的选择,本文将针对阿里云服务器的经济型、通用算力型、计算型、通用型和内存型实例,介绍它们的性能特性以及对应的使用场景,以供大家参考和选择。
|
11月前
|
存储 缓存
.NET 6中Startup.cs文件注入本地缓存策略与服务生命周期管理实践:AddTransient, AddScoped, AddSingleton。
记住,选择正确的服务生命周期并妥善管理它们是至关重要的,因为它们直接影响你的应用程序的性能和行为。就像一个成功的建筑工地,工具箱如果整理得当,工具选择和使用得当,工地的整体效率将会大大提高。
377 0

推荐镜像

更多
  • DNS