Java写Xml文件中文乱码的问题不仅仅是设置Encoding那么简单,请看如下实例:
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.OutputStreamWriter; 4 import java.io.Writer; 5 6 import javax.xml.parsers.DocumentBuilder; 7 import javax.xml.parsers.DocumentBuilderFactory; 8 import javax.xml.transform.OutputKeys; 9 import javax.xml.transform.Result; 10 import javax.xml.transform.Source; 11 import javax.xml.transform.Transformer; 12 import javax.xml.transform.TransformerConfigurationException; 13 import javax.xml.transform.TransformerException; 14 import javax.xml.transform.TransformerFactory; 15 import javax.xml.transform.dom.DOMSource; 16 import javax.xml.transform.stream.StreamResult; 17 18 import org.w3c.dom.Document; 19 import org.w3c.dom.Element; 20 import org.w3c.dom.Text; 21 22 public class WriteXml { 23 private void writeXMLFile(String xmlfile) { 24 File file = new File("E:/tryfile/xml"); 25 file.listFiles(); 26 if(!file.exists()) { 27 file.mkdirs(); 28 } 29 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 30 DocumentBuilder dbuilder = null; 31 try { 32 dbuilder = dbf.newDocumentBuilder(); 33 }catch(Exception ex) { 34 ex.printStackTrace(); 35 } 36 37 Document doc = dbuilder.newDocument(); 38 Element root = doc.createElement("学生花名册"); 39 doc.appendChild(root); 40 41 Element stu = doc.createElement("学生"); 42 stu.setAttribute("性别","男"); 43 root.appendChild(stu); 44 45 Element stu_name = doc.createElement("姓名"); 46 stu.appendChild(stu_name); 47 Text name_text = doc.createTextNode("罗文雯"); 48 stu_name.appendChild(name_text); 49 50 Element stu_age = doc.createElement("年龄"); 51 stu.appendChild(stu_age); 52 Text age_text = doc.createTextNode("25"); 53 stu_age.appendChild(age_text); 54 try { 55 FileOutputStream fos = new FileOutputStream(xmlfile + "/test.xml"); 56 OutputStreamWriter osw = new OutputStreamWriter(fos); // 注意。。。 57 callDomWriter(doc, osw, "UTF-8"); 58 osw.close(); 59 fos.close(); 60 }catch(Exception ex) { 61 ex.printStackTrace(); 62 } 63 } 64 65 private void callDomWriter(Document dom , Writer writer, String encoding) { 66 try { 67 Source source = new DOMSource(dom); 68 Result res = new StreamResult(writer); 69 Transformer xformer = TransformerFactory.newInstance().newTransformer(); 70 xformer.setOutputProperty(OutputKeys.ENCODING, encoding); 71 xformer.transform(source, res); 72 }catch (TransformerConfigurationException e) { 73 e.printStackTrace(); 74 } catch (TransformerException e) { 75 e.printStackTrace(); 76 } 77 } 78 79 public static void main(String []args) { 80 WriteXml writeins = new WriteXml(); 81 String outfile = "E:/tryfile/xml"; 82 writeins.writeXMLFile(outfile); 83 System.out.println("finished"); 84 } 85 }