我在arraylist中需要一些3000個元素,需要將這3000個元素寫入xml。 在eclipse中執行需要20分鐘的時間。 有沒有任何有效的方法來做到這一點? 或對我的代碼進行任何修改?將文本寫入XML需要很長時間--Java
在ArrayList中的元素都應該在今後的成長......
我的代碼片斷..
---------------------------------------------------
---------------------------------------------------
for(int i=0;i<candidates.size();i++)//Candidates is my arraylist
{
String text=candidates.get(i);
//System.out.println(text);
text=text+"\n";
file= new File("./test.xml");
WriteToXML wr= new WriteToXML(file,"fullname",text);
}
-------------------------------------------------------
-------------------------------------------------------
//WritetoXML class constructor
public WriteToXML(File xml,String tag,String data)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(xml)));
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName(tag);
Element fn= (Element) node1.item(0);
Text text = doc.createTextNode(data);
fn.appendChild(text);
printtoXML(doc);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static final void printtoXML(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xml);
tf.transform(source, result);
String xmlString = sw.toString();
File file= new File(xml);
FileWriter fw=new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(xmlString);
bw.flush();
bw.close();
}
http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html –
你的代碼太慢了,因爲你總是實例化每個方法調用的許多對象(File,FileWriter ....)到寫入xml文件。如果你在文件中寫入一次而不是3000次,我想它會快得多,因爲那麼你必須打開一次(關閉和寫入)而不是3000次。 – Akkusativobjekt
你有其他建議嗎? – user2814979