您的位置:首页 > 其它

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

2015-01-01 16:29 267 查看
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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: