用的是DOM,代碼丑了一點,將就著看吧,不過還是能用的
1 import java.io.File;
2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import javax.xml.parsers.DocumentBuilder;
6 import javax.xml.parsers.DocumentBuilderFactory;
7 import javax.xml.parsers.ParserConfigurationException;
8 import javax.xml.transform.OutputKeys;
9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerException;
11 import javax.xml.transform.TransformerFactory;
12 import javax.xml.transform.dom.DOMSource;
13 import javax.xml.transform.stream.StreamResult;
14 import org.w3c.dom.Document;
15 import org.w3c.dom.Element;
16 import org.w3c.dom.Node;
17 import org.w3c.dom.NodeList;
18 import org.xml.sax.SAXException;
19
20 public class ChatRecord {
21
22 private Document document;
23 private String filename;
24 Element root;
25
26 public ChatRecord (String name)
27 {
28 filename = name;
29 }
30
31 /*
32 * If there is no chat record, we should start a new one
33 * But make sure that this method will only be executed ONCE!!!
34 */
35 public void startNewRecord() throws ParserConfigurationException
36 {
37 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
38 DocumentBuilder builder = factory.newDocumentBuilder();
39 document = builder.newDocument();
40 root = document.createElement("ChatRecord");
41 document.appendChild(root);
42 toSave();
43 }
44
45 /*
46 * Save the XML to disk
47 */
48 public void toSave(){
49 try{
50 TransformerFactory tf = TransformerFactory.newInstance();
51 Transformer transformer = tf.newTransformer();
52 DOMSource source = new DOMSource(document);
53 transformer.setOutputProperty(OutputKeys.ENCODING,"GB2312");
54 //transformer.setOutputProperty(OutputKeys.INDENT,"yes");
55 PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
56 StreamResult result = new StreamResult(pw);
57 transformer.transform(source,result);
58 pw.close();
59 }
60 catch(TransformerException mye){
61 mye.printStackTrace();
62 }
63 catch(IOException exp){
64 exp.printStackTrace();
65 }
66 }
67
68
69 /*
70 * Read the chat record from a XML
71 */
72 public void print()
73 {
74 try {
75
76 // create DocumentBuilderFactory
77 DocumentBuilderFactory factory =
78 DocumentBuilderFactory.newInstance();
79
80 // create DocumentBuilder
81 DocumentBuilder builder = factory.newDocumentBuilder();
82
83 // obtain document object from XML document
84 Document document = builder.parse(
85 new File( filename) );
86
87 // get root node
88 Node root = document.getDocumentElement();
89
90 NodeList childNodes = root.getChildNodes();
91 Node currentNode;
92
93 for ( int i = 0; i < childNodes.getLength(); i++ ) {
94
95 currentNode = childNodes.item( i );
96
97 // print node name of each child element
98 System.out.println( currentNode.getNodeName() + " " + currentNode.getFirstChild().getNodeValue());
99 }
100
101 }
102
103 // handle exception creating DocumentBuilder
104 catch ( ParserConfigurationException parserError ) {
105 System.err.println( "Parser Configuration Error" );
106 parserError.printStackTrace();
107 }
108
109 // handle exception reading data from file
110 catch ( IOException fileException ) {
111 System.err.println( "File IO Error" );
112 fileException.printStackTrace();
113 }
114
115 // handle exception parsing XML document
116 catch ( SAXException parseException ) {
117 System.err.println( "Error Parsing Document" );
118 parseException.printStackTrace();
119 }
120 }
121
122
123 /*
124 * If there is already a chat record
125 * use this method to update it
126 */
127 public void update(String time, String sender, String receiver, String textcontent)
128 {
129 try {
130
131 // create DocumentBuilderFactory
132 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
133
134 // create DocumentBuilder
135 DocumentBuilder builder = factory.newDocumentBuilder();
136
137 // obtain document object from XML document
138 document = builder.parse(
139 new File( filename ) );
140
141 Node thisroot = document.getFirstChild();
142 Element mytime = document.createElement("Time");
143 mytime.appendChild(document.createTextNode(time));
144 thisroot.appendChild(mytime);
145
146 Element Sender = document.createElement("Sender");
147 Sender.appendChild(document.createTextNode(sender));
148 thisroot.appendChild(Sender);
149
150 Element Receiver = document.createElement("Receiver");
151 Receiver.appendChild(document.createTextNode(receiver));
152 thisroot.appendChild(Receiver);
153
154 Element content = document.createElement("Content");
155 content.appendChild(document.createTextNode(textcontent));
156 thisroot.appendChild(content);
157
158 }
159 // handle exception creating DocumentBuilder
160 catch ( ParserConfigurationException parserError ) {
161 System.err.println( "Parser Configuration Error" );
162 parserError.printStackTrace();
163 }
164
165 // handle exception reading data from file
166 catch ( IOException fileException ) {
167 System.err.println( "File IO Error" );
168 fileException.printStackTrace();
169 }
170
171 // handle exception parsing XML document
172 catch ( SAXException parseException ) {
173 System.err.println( "Error Parsing Document" );
174 parseException.printStackTrace();
175 }
176 }
177 }
178
說說問題吧,因為要寫一個聊天記錄的XML,就好象MSN的那個聊天記錄一樣,于是當(dāng)然要不斷的續(xù)寫
但是我沒找到DOM的API來完成這個功能,找了很久很久,想了很多辦法
最后還是用了最SB的辦法,parseXML文件,append新的Element,然后重新寫出去
但是這樣當(dāng)XML文件打了一會,為了寫一條聊天記錄就要進(jìn)行大量的IO操作,這樣現(xiàn)在是不合理的
其實可以直接在文件里面println,這樣就不用進(jìn)行那么多無用的讀寫了
但是我想DOM應(yīng)該不至于連這么有用的API都沒有吧?
其實我看DOM的API也就一個晚上,而且對DOM整體的架構(gòu)還不是很了解
不知道里面的parse是怎么實現(xiàn)的,或許人家已經(jīng)想到了我這個問題……
不知道,反正現(xiàn)在只能暫時這樣實現(xiàn)了,如果真的是為了性能的考慮,那倒是可以自己寫一個println的方法,直接把新的元素追加上去
有空去好好學(xué)學(xué)XML吧
JAVA還是基本功不夠好啊,很多諸如I/O Stream之類的東西,里面的類都還不是很清楚
當(dāng)初看得Design Pattern現(xiàn)在全忘光了……,真是對不起我的媳婦兒啊
Anyway,有時間再說吧……