公司需要通过xml将数据库中的数据导出来,dom4j当然是最好的选择,可是写一直乱码,下面是我的代码:
public void writeXml(Document document, String fileName) {
try {
FileOutputStream fileWriter = new FileOutputStream(fileName);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
document.setXMLEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
xmlWriter.write(document);
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public Document readXml(String fileName) {
File inputXml = new File(fileName);
if (inputXml.exists()) {
try {
SAXReader saxReader = new SAXReader();
FileInputStream ifile = new FileInputStream(inputXml);
InputStreamReader ir = new InputStreamReader(ifile, "UTF-8");
Document document = saxReader.read(ir);
document.setXMLEncoding("UTF-8");
return document;
} catch (DocumentException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("file is not exist");
}
return null;
}
可是还是一直出错,最后终于发现了,原来刚开始测试的时候我的项目默认是GBK编码的,后来我改成了UTF-8,但是我测试程序中的中文看着没有问题,其实还是GBK的编码,只要把测试中的中文删除重写下就没问题了,这也算myeclipse中的一个小小的bug吧