|
DOM4J写文件出现乱码,重新编码也不行,写了个测试的 代码如下
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class Test {
public static void main(String[] args)
{
try{
SAXReader reader = new SAXReader();
Document document = reader.read("c:/Demo.txt");
Element root = document.getRootElement();
String a="研发部";
Element newElement=root.addElement("Department")
.addAttribute("value",new String(a.getBytes(),"UTF-8"))
;
// OutputFormat format=new OutputFormat(" ",true,"GBK");
//使用 format能解决问题但是,XML规定为UTF-8
XMLWriter writer = new XMLWriter(
new FileOutputStream(new File("c:/Demo.txt")));
//new FileWriter("c:/Demo.txt"));
//使用FileWriter并不正确,DOM4J并未转码,写第二次时会报错
writer.write( document );
writer.close();
}catch(Exception e){System.out.println(e.getMessage());}
}
}
Demo.txt
<?xml version="1.0" encoding="UTF-8"?>
<Company>
</Company> |
|