首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

dom4j乱码出现异常

2012-10-31 
dom4j乱码出现错误package com.havenliu.blog?import java.io.Fileimport java.io.FileNotFoundExceptio

dom4j乱码出现错误

package com.havenliu.blog;?import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.UnsupportedEncodingException;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;?public class Dom4jXmlOper {? public static void createXml(File file) {  XMLWriter writer = null;  SAXReader reader = new SAXReader();?  OutputFormat format = OutputFormat.createPrettyPrint();  format.setEncoding("utf-8");//设置XML文件的编码格式,如果有中文可设置为GBK或UTF-8?  Document _document = DocumentHelper.createDocument();  Element _root = _document.addElement("userinfo");  Element user = _root.addElement("user");  user.addAttribute("id", "001");  Element name = user.addElement("name");  name.setText("张三");  Element age = user.addElement("age");  age.setText("28");  Element sex = user.addElement("sex");  sex.setText("男");  Element email = user.addElement("email");  email.setText("abc@abc.com");?  //如果上面设置的xml编码类型为GBK,则应当用FileWriter来构建xml文件,否则会出现中文连码问题  /*   try {   writer = new XMLWriter(new FileWriter(file), format);  } catch (IOException e1) {   e1.printStackTrace();  }  */?  //如果上面设置的xml编码类型为utf-8,则应当用FileOutputStream来构建xml文件,否则还是会出现乱码问题  FileOutputStream fos = null;  try {   fos = new FileOutputStream(file);  } catch (FileNotFoundException e) {   e.printStackTrace();  }  try {   writer = new XMLWriter(fos, format);  } catch (UnsupportedEncodingException e) {   e.printStackTrace();  }  try {   writer.write(_document);   writer.close();  } catch (IOException e) {   e.printStackTrace();  } } public static void main(String[] args) {  String filePath = "d:\\temp\\user.xml";//生产的XML文件位置  File file = new File(filePath);  Dom4jXmlOper.createXml(file); }?}

热点排行