Dom4j设置编码的问题

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值