dom4j设置编码,使用OutputFormat类
注意的就是
OutputFormat format = OutputFormat.createPrettyPrint();// 创建文件输出的时候,自动缩进的格式
format.setEncoding("UTF-8");//设置编码
XMLWriter writer;
StringBuilder filePath = new StringBuilder();
filePath.append(getExportPath());
filePath.append(fileName);
try {
File file = new File(filePath.toString());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
/**
* 必须要用FileOutputStream 才能转码,用FileWriter不能转码
* FileWriter此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。
* 要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter。
* FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream。
*/
writer = new XMLWriter(new FileOutputStream(file),format);
writer.write(doc);
writer.close();
// set permission
FileHelper.setAllPermission(file,true);
} catch (IOException e) {
log.error(e.getMessage());
return false;
}
注意的就是
writer = new XMLWriter(new FileOutputStream(file),format);
我开始就是没注意用FileWriter没有用FileOutputStream 所有一直没有正确的转码。
必须要用FileOutputStream 才能转码,用FileWriter不能转码 ,以下是jdk文档中给出的解释和提示
FileWriter此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。
要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter。
FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream。