dom4j解析xml时报出文件提前结束
在写javaweb小项目的时候,用dom4j解析xml报出如下错误:
org.dom4j.DocumentException:Error ....... Nested exception: 文件提前结束。

1 package com.miragic.utils;
2
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5
6 import java.io.UnsupportedEncodingException;
7
8 import org.dom4j.Document;
9 import org.dom4j.DocumentException;
10 import org.dom4j.io.OutputFormat;
11 import org.dom4j.io.SAXReader;
12 import org.dom4j.io.XMLWriter;
13
14 //操作XML文件的方法
15 public class JaxpUtils {
16
17 static String path;
18
19 static {
20 path=JaxpUtils.class.getClassLoader().getResource("users.xml").getPath();
21
22 }
23 public static Document getDocument() {
24 //创建一个dom4j解析器
25 try {
26 SAXReader reader=new SAXReader();
27 Document document=reader.read(path);
28 return document;
29 } catch (DocumentException e) {
30 // TODO Auto-generated catch block
31 e.printStackTrace();
32 }
33 return null;
34 }
35
36 public static void write2xml(Document document) {
37
38 try {
39 XMLWriter writer=new XMLWriter(new FileOutputStream(path),OutputFormat.createPrettyPrint());
40
41 } catch (UnsupportedEncodingException e) {
42 // TODO Auto-generated catch block
43 e.printStackTrace();
44 } catch (FileNotFoundException e) {
45 // TODO Auto-generated catch block
46 e.printStackTrace();
47 }
48
49 }
50
51 }

百度了好久,有的说是xml没有根目录,有的说是xml格式不对,然后我检查了xml格式并且重写了好几次,但都木有用,以下为xml代码:
| 1 2 3 4 |
|
同时,还排除了一下编码的错误,并没有发现异常.
错误原因:解析xml没有关流
解决方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
加了两行
writer.write(document);
writer.close();
问题解决.
总结:一个简单的小错误,说白了还是理解的不够透彻导致写代码的时候丢三落四,好歹问题解决了,找bug的时候内心真的是绝望啊!!!!!!!
本文介绍使用DOM4j解析XML文件时遇到的文件提前结束错误,分析原因并提供解决方案,涉及XML文件读写和异常处理。
1510

被折叠的 条评论
为什么被折叠?



