dom4j将生成好的doc写入磁盘,并解决中文乱码

来源:互联网 发布:淘宝站外活动销量 编辑:程序博客网 时间:2024/06/10 14:52
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


public class XmlWriter {
private void writeDocument(Document document, String dest) {
XMLWriter xmlWriter = null;
try {
PrintWriter printWriter = new PrintWriter(dest, "UTF-8");
OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
xmlWriter = new XMLWriter(printWriter, xmlFormat);
xmlWriter.write(document);
xmlWriter.flush();
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != xmlWriter) {
xmlWriter.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


public static void main(String[] args) throws Exception {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
root.addElement("child").setText("i am a child");
String dest = "C:"+File.separator+"temp"+File.separator+"世界是我们的.xml";
System.out.println(dest);
File file = new File(dest);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
XmlWriter xw = new XmlWriter();
xw.writeDocument(doc, dest);
}
}
0 0