Dom4j设置编码的问题(转载)

来源:互联网 发布:托管淘宝店铺 编辑:程序博客网 时间:2024/06/06 04:02
dom4j设置编码,使用OutputFormat类
[java] view plain copy
  1.           OutputFormat format = OutputFormat.createPrettyPrint();// 创建文件输出的时候,自动缩进的格式                      
  2.    format.setEncoding("UTF-8");//设置编码    
  3.    XMLWriter writer;  
  4.      
  5.    StringBuilder filePath = new StringBuilder();   
  6.    filePath.append(getExportPath());  
  7.    filePath.append(fileName);  
  8. try {  
  9.     File file = new File(filePath.toString());  
  10.     if (!file.getParentFile().exists()) {  
  11.         file.getParentFile().mkdirs();  
  12.     }  
  13.     /** 
  14.      * 必须要用FileOutputStream 才能转码,用FileWriter不能转码 
  15.      * FileWriter此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。 
  16.      * 要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter。 
  17.      * FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream。 
  18.      */  
  19.     writer = new XMLWriter(new FileOutputStream(file),format);  
  20.     writer.write(doc);    
  21.     writer.close();    
  22.       
  23.     // set permission  
  24.     FileHelper.setAllPermission(file,true);  
  25. catch (IOException e) {  
  26.     log.error(e.getMessage());  
  27.     return false;  
  28. }    

注意的就是
[java] view plain copy
  1. writer = new XMLWriter(new FileOutputStream(file),format);  

我开始就是没注意用FileWriter没有用FileOutputStream 所有一直没有正确的转码。

必须要用FileOutputStream 才能转码,用FileWriter不能转码 ,以下是jdk文档中给出的解释和提示

FileWriter此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。 

要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter。 

FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream。