java读取文件目录结构并生成xml树
- 格式:doc
- 大小:47.50 KB
- 文档页数:3
java读取XML⽂件的四种⽅法总结(必看篇)JAVA操作XML⽂档主要有四种⽅式,分别是DOM、SAX、JDOM和DOM4J,DOM和SAX是官⽅提供的,⽽JDOM和DOM4J 则是引⽤第三⽅库的,其中⽤的最多的是DOM4J⽅式。
运⾏效率和内存使⽤⽅⾯最优的是SAX,但是由于SAX是基于事件的⽅式,所以SAX⽆法在编写XML的过程中对已编写内容进⾏修改,但对于不⽤进⾏频繁修改的需求,还是应该选择使⽤SAX。
下⾯基于这四种⽅式来读取XML⽂件。
第⼀,以DOM的⽅式实现。
package xmls;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import java.io.File;import java.io.IOException;/*** Created by lenovo on 2017-6-3.*/public class DOMReadDemo {public static void main(String[] args){DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();try{DocumentBuilder db = dbf.newDocumentBuilder();Document document = db.parse("src/xmls/DOM.xml");NodeList booklist = document.getElementsByTagName("book");for(int i = 0; i < booklist.getLength(); i++){System.out.println("--------第" + (i+1) + "本书----------");Element ele = (Element) booklist.item(i);NodeList childNodes= ele.getChildNodes();for(int j = 0; j < childNodes.getLength(); j++){Node n = childNodes.item(j);if(n.getNodeName() != "#text"){System.out.println(n.getNodeName() + ":" + n.getTextContent());}}System.out.println("---------------------------------");}}catch (ParserConfigurationException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}catch (SAXException e){e.printStackTrace();}}}第⼆,以SAX的⽅式实现。
java读取xml配置⽂件(⼩结)使⽤DOM解析XML⽂档时,需要读⼊整个XML⽂档,然后在内存中创建DOM树,⽣成DOM树上的每个节点对象。
只有在整个DOM树创建完毕后,我们才能做其他的操作,即使我们只需要修改根元素节点的第⼆个⼦节点,仍然需要在进⾏这个⼩⼩的修改之间分析整个⽂档,在内存中构建⽂档树。
当XML⽂档⽐较⼤时,构建DOM树将花费⼤量的时间和内存。
⼀种替代的技术就是使⽤SAX,SAX允许你在读取⽂档的时候,即对它进⾏处理,解析完毕处理也就完成了,不必等待整个⽂档被分析存储之后才进⾏操作。
三步过程为了使⽤ XML ⽂件中的信息,必须解析⽂件以创建⼀个 Document 对象。
Document 对象是⼀个接⼝(??为了统⼀吗 ),因⽽不能直接将它实例化;⼀般情况下,应⽤程序会相应使⽤⼀个⼯⼚。
准确的过程因实现⽽异,但是基本思想是相同的。
(同样,Level 3 标准化了这个任务。
)在这个例⼦ Java 环境中,解析⽂件是⼀个三步过程:1.创建 DocumentBuilderFactory。
DocumentBuilderFactory 对象创建 DocumentBuilder。
2.创建 DocumentBuilder。
DocumentBuilder 执⾏实际的解析以创建 Document 对象。
3.解析⽂件以创建 Document 对象。
现在您可以开始构建应⽤程序了。
基本的应⽤程序⾸先创建⼀个基本的应⽤程序,即⼀个名为 OrderProcessor 的类。
『『 『 『第⼀步是⽣成⼀个DocumentBuilderFactory对象,newInstance()是静态⽅法,所以可以直接类名点调⽤。
第⼆步是⽤⼯⼚⽣成⼀个DocumentBuilder对象,但是newDocumentBuilder()是抽象⽅法,还没实现,在这⾥就可以调⽤了吗?还是像你以前说的,只要能产⽣⼀个抽象类的对象,那么这个抽象类的所以抽象⽅法就都已经实现了?是这样吗newDocumentBuilder()抽象⽅法肯定会被⾮抽象⼦类实现,这就发⽣了多态,执⾏时调⽤⼦类的重写后的⽅法public class DocumentBuilderFactoryImpl extends DocumentBuilderFactory {......................}sun的newInstance()⽅法public static DocumentBuilderFactory newInstance() {try {return (DocumentBuilderFactory) FactoryFinder.find(/* The default property name according to the JAXP spec */"javax.xml.parsers.DocumentBuilderFactory",/* The fallback implementation class name */".apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");} catch (FactoryFinder.ConfigurationError e) {throw new FactoryConfigurationError(e.getException(),e.getMessage());}}它应该是⽤反射返回了⼀个DocumentBuilderFactoryImpl的实例,然后⽤DocumentBuilderFactory强转,也就是:DocumentBuilderFactory.newInstance()返回⼀个Object类型的DocumentBuilderFactory实例,下⾯的就不⽤说了吧!』import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import java.io.File;import org.w3c.dom.Document;public class OrderProcessor {public static void main (String args[]) {File docFile = new File("orders.xml");Document doc = null;try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();doc = db.parse(docFile);} catch (Exception e) {System.out.print("Problem parsing the file: "+e.getMessage());}}}⾸先,Java 代码导⼊必要的类,然后它创建 OrderProcessor 应⽤程序。
使用要导入dom4j-1.6.1.jar文件我的dom4j文件在讲解生成xml 1:先通过DocumentHelper类的.createDocument()方法生成Document文件2:接着通过DocumentHelper类的createElement("根节点字符串形式")创建根节点3:通过通过生成的Document的实例的setRootElement(根节点)设置根节点4:接着可以通过Document的实例的getRootElement()方法得到根节点5:接着通过根节点(Element类的实例)的.addElement("子节点的字符串形式")添加子节点6:通过节点类(Element类的实例)的setText("字符串“)设置节点对应的值7:通过Document类的实例的.asXML();的方式的得到xml字符串;(注意:xml 是字符串String的形式。
可以设置几个同名的根节点(<user>username1<user><<user>username2<user>)解析时通过Elment的.elementIterator("user");方法得到迭代器)解析xml 1:通过new SAXReader();得到SAXReader的一个实例2:通过StringReader(参数是字符串)将xml字符串转化为一个Reader字符输入流3:通过SAXReader的实例.read(参数是个Reader)得到得到Document4:通过Document的getRootElement()方法得到根节点(Element类的实例)5:通过根节点的element("子节点的字符串形式")方法得到子节点(若有多个同名子节点通过根节点的.elementIterator("user")得到同名节点迭代器)6:通过节点的getTxt();方法得到节点的值生成xml 例子:private static Document constructDocument()//此处会被下面调用{Document document = DocumentHelper.createDocument();Element root = DocumentHelper.createElement("message");document.setRootElement(root);return document;}document文件。
java读取xml4种方法XML 文件格式如下:测试方法:采用 JSP 端调用Bean(至于为什么采用JSP来调用,请参考:/rosen/archive/2004/10/15/138324.aspx),让每一种方案分别解析10K、100K、1000K、10000K的 XML 文件,计算其消耗时间(单位:毫秒)。
JSP 文件:测试1、首先出场的是 DOM(JAXP Crimson 解析器)DOM 是用与平台和语言无关的方式表示 XML 文档的官方 W3C 标准。
DOM 是以层次结构组织的节点或信息片断的集合。
这个层次结构允许开发人员在树中寻找特定信息。
分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作。
由于它是基于信息层次的,因而 DOM 被认为是基于树或基于对象的。
DOM 以及广义的基于树的处理具有几个优点。
首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改。
它还可以在任何时候在树中上下导航,而不是像 SAX 那样是一次性的处理。
DOM 使用起来也要简单得多。
另一方面,对于特别大的文档,解析和加载整个文档可能很慢且很耗资源,因此使用其他手段来处理这样的数据会更好。
这些基于事件的模型,比如 SAX。
Bean文件:10k消耗时间:265 203 219 172100k消耗时间:9172 9016 8891 90001000k消耗时间:691719 675407 708375 73965610000k消耗时间:OutOfMemoryError2、接着是 SAX这种处理的优点非常类似于流媒体的优点。
分析能够立即开始,而不是等待所有的数据被处理。
而且,由于应用程序只是在读取数据时检查数据,因此不需要将数据存储在内存中。
这对于大型文档来说是个巨大的优点。
事实上,应用程序甚至不必解析整个文档;它可以在某个条件得到满足时停止解析。
一般来说,SAX 还比它的替代者 DOM 快许多。
* Inc.* Copyright (c) 2005-2008 All Rights Reserved.*/package com.alipay.client.base;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;/***** @author feng.chenf* @version $Id: ClientConfig.java, v 0.1 2008-12-24 ????09:31:39 feng.chenf Exp $ */public class ClientConfig {/*** ????????????????????? ????????https://*/private String serverUrl = "http://115.124.16.16";/*** ????????????????????? ???????????????? ?????443???private String serverPort = "80";/*** ?????partnerId*/private String partnerId = "";/*** ??????????ú?*/private String secId = "";/*** ???????*/private String prikey = "";/*** ???????*/private String pubkey = "";/*** ????????????????????*/private String alipayVeriPubKey = ""; /*** ?????????????????????????private String alipayEncPubKey = "";/*** ?????? ?????????????RSA*/private String signAlgo = "RSA";/*** ??????? ?????????????RSA*/private String encryptAlgo = "RSA";public ClientConfig() {try {InputStream iss = this.getClass().getClassLoader().getResourceAsStream( "com/alipay/client/config/config.xml");DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); DocumentBuilder dombuilder = domfac.newDocumentBuilder();Document doc = dombuilder.parse(iss);Element rootElement = doc.getDocumentElement();NodeList paramNode = doc.getElementsByTagName("partnerId");partnerId = paramNode.item(0).getFirstChild().getNodeValue().trim(); NodeList secNode = doc.getElementsByTagName("secId");secId = secNode.item(0).getFirstChild().getNodeValue().trim();NodeList signAlgoNode = doc.getElementsByTagName("signAlgo");this.signAlgo = signAlgoNode.item(0).getFirstChild().getNodeValue().trim();NodeList prikeyNode = doc.getElementsByTagName("prikey");this.prikey = prikeyNode.item(0).getFirstChild().getNodeValue().trim();NodeList pubkeyNode = doc.getElementsByTagName("pubkey");this.pubkey = pubkeyNode.item(0).getFirstChild().getNodeValue().trim();NodeList alipayVeriPubKeyNode = doc.getElementsByTagName("alipayVeriPubKey");this.alipayVeriPubKey =alipayVeriPubKeyNode.item(0).getFirstChild().getNodeValue().trim();NodeList alipayEncPubKeyNode = doc.getElementsByTagName("alipayEncPubKey");this.alipayEncPubKey = alipayEncPubKeyNode.item(0).getFirstChild().getNodeValue().trim();} catch (Exception e) {//??????//??????????? ????????????e.printStackTrace();}}/*** @return Returns the serverUrl.*/public String getServerUrl() {return serverUrl;}/*** @param serverUrl The serverUrl to set.*/this.serverUrl = serverUrl;}/*** @return Returns the serverPort.*/public String getServerPort() {return serverPort;}/*** @param serverPort The serverPort to set.*/public void setServerPort(String serverPort) { this.serverPort = serverPort;}/*** @return Returns the partnerId.*/public String getPartnerId() {return partnerId;}/*** @param partnerId The partnerId to set.*/this.partnerId = partnerId;}/*** @return Returns the secId.*/public String getSecId() {return secId;}/*** @param secId The secId to set.*/public void setSecId(String secId) { this.secId = secId;}/*** @return Returns the prikey.*/public String getPrikey() {return prikey;}/*** @param prikey The prikey to set. */public void setPrikey(String prikey) { this.prikey = prikey;}/*** @return Returns the pubkey.*/public String getPubkey() {return pubkey;}/*** @param pubkey The pubkey to set.*/public void setPubkey(String pubkey) { this.pubkey = pubkey;}/*** @return Returns the signAlgo.*/public String getSignAlgo() {return signAlgo;}/*** @param signAlgo The signAlgo to set. */public void setSignAlgo(String signAlgo) {this.signAlgo = signAlgo;}/*** @return Returns the encryptAlgo.*/public String getEncryptAlgo() {return encryptAlgo;}/*** @param encryptAlgo The encryptAlgo to set.*/public void setEncryptAlgo(String encryptAlgo) {this.encryptAlgo = encryptAlgo;}/*** @return Returns the alipayVeriPubKey.*/public String getAlipayVeriPubKey() {return alipayVeriPubKey;}/*** @param alipayVeriPubKey The alipayVeriPubKey to set. */public void setAlipayVeriPubKey(String alipayVeriPubKey) { this.alipayVeriPubKey = alipayVeriPubKey;}/*** @return Returns the alipayEncPubKey.*/public String getAlipayEncPubKey() {return alipayEncPubKey;}/*** @param alipayEncPubKey The alipayEncPubKey to set.*/public void setAlipayEncPubKey(String alipayEncPubKey) { this.alipayEncPubKey = alipayEncPubKey;}}。
Java读取XML⽂件使⽤Java读取XML⽂件有四种⽅式:1. DOM2. SAX3. JDOM4. DOM4jbook.xml⽂件内容:1<?xml version="1.0" encoding="UTF-8"?>2<书架>3<书>4<书名编号="a_1">JavaWeb程序开发⼊门</书名>5<作者分类="AA">传智播客</作者>6<售价单位="元">60</售价>7</书>8<书>9<书名编号="a_2">JavaWeb从⼊门到精通</书名>10<作者分类="BB">明⽇科技</作者>11<售价>80</售价>12</书>13<书>14<书名编号="a_3">计算机⽂化基础</书名>15<作者分类="CC">⼭东商务</作者>16<售价>40</售价>17</书>18</书架>1.DOMDOM 解析 XML 的步骤:1) 创建⼀个 DocumentBuilderFactory 的对象。
2) 创建⼀个 DocumentBuilder 对象。
3) 通过DocumentBuilder的parse(...)⽅法得到Document对象。
4) 通过 getElementsByTagName(...)⽅法获取到节点的列表。
5) 通过 for 循环遍历每⼀个节点。
6) 得到每个节点的属性和属性值。
7) 得到每个节点的节点名和节点值。
Java XML处理解析和生成XML数据Java作为一种广泛使用的编程语言,提供了丰富的API和工具来处理和操作XML数据。
本文将介绍Java中处理和解析XML数据的基本方法,并探讨如何使用Java生成XML数据。
一、XML简介XML(可扩展标记语言)是一种用于描述数据的标记语言,它的设计目标是传输数据而不仅仅是显示数据。
XML以一种结构化的方式存储数据,使得数据具有良好的可读性和可扩展性。
二、XML解析XML解析是指将XML数据转换为Java程序可以理解和处理的格式。
Java提供了几种XML解析方法,包括DOM(文档对象模型)、SAX(简单API for XML)和StAX(流API for XML)。
1. DOM解析DOM解析是最常用和最常见的XML解析方法之一。
DOM将XML文档视为一个树形结构,通过解析整个文档并将其加载到内存中,以方便对数据的操作和访问。
使用DOM解析XML的基本步骤如下:(1)创建一个DocumentBuilder对象。
(2)使用DocumentBuilder对象的parse()方法解析XML文件,返回一个Document对象。
(3)通过Document对象获取XML文件中的节点和元素。
以下是一个使用DOM解析XML的示例代码:```DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document document = builder.parse(new File("example.xml"));// 获取根节点Element rootElement = document.getDocumentElement();// 获取子节点NodeList nodeList = rootElement.getElementsByTagName("book");for (int i = 0; i < nodeList.getLength(); i++) {Element bookElement = (Element) nodeList.item(i);String title =bookElement.getElementsByTagName("title").item(0).getTextContent( );String author =bookElement.getElementsByTagName("author").item(0).getTextContent();System.out.println("Title: " + title + ", Author: " + author);}```2. SAX解析SAX解析是一种基于事件驱动的解析方法。
java读取文件目录结构并生成xml树,具体实现代码如下:
package org.wendong.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 多线程读取本地文件中的所有文件目录结构及文件大小
* @author Administrator
*
*/
public class ThreadReader extends Thread {
@Override
public void run() {
try {
Long start = System.currentTimeMillis();
String name = Thread.currentThread().getName();
System.err.println("当前线程名:"+name);
File file = new File(name);
Document doc = DocumentHelper.createDocument();
Element el = doc.addElement(file.getName());
el = getFile(file, el);
File docFile = new File(name+"/目录结构.xml");
if(!docFile.exists()){
docFile.createNewFile();
FileOutputStream fos = new FileOutputStream(docFile);
fos.write(doc.asXML().getBytes());
fos.flush();
fos.close();
}
Long end = System.currentTimeMillis();
System.out.println("目录建立成功! 耗时:"+(end - start)+"ms");
} catch (Exception e) {
System.err.println("异常"+e);
}
}
public static Element getFile(File file, Element el){
try {
File[] list = file.listFiles();
if(list != null && list.length > 0){
for(File f : list){
if(f.isDirectory()){//目录
Element e = el.addElement("Folder");
e.addAttribute("name",
f.getName());
e.addAttribute("lastModify", parseDate(
stModified()));
getFile(f, e);
}else{//文件
Element e = el.addElement("File");
e.addAttribute("name",
f.getName());
e.addAttribute("lastModify", parseDate(
stModified()));
e.addAttribute("size", parseSize(
f.length()));
}
System.out.println(el.asXML());
}
}
return el;
} catch (Exception e) {
System.err.println("异常"+e);
}
return null;
}
public static String parseSize(Long l){
String strSize = "0";
if(l < 1000){
strSize = l + "B";
}else if(l < 1000*1000){
strSize = l/1000+"."+l%1000+"K";
}else if(l < 1000*1000*1000){
strSize = l/(1000*1000)+"."+l%(1000*1000)+"M";
}else if(l < 1000*1000*1000*1000){
strSize = l/(1000*1000*1000)+"."+l%(1000*1000*1000)+"G";
}
return strSize;
}
public static String parseDate(Long l){
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(l);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.format(calendar.getTime());
}
public static void main(String[] args) {
try {
File[] file = File.listRoots();
for(File f : file){
ThreadReader tr = new ThreadReader();
tr.setName(f.getName());
tr.setPriority(MAX_PRIORITY);
tr.start();
}
} catch (Exception e) {
System.err.println("异常"+e);
}
}
}。