dom4j中文乱码问题

公司需要通过xml将数据库中的数据导出来,dom4j当然是最好的选择,可是写一直乱码,下面是我的代码:

public void writeXml(Document document, String fileName) {
        try {
            FileOutputStream fileWriter = new FileOutputStream(fileName);

            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            
            document.setXMLEncoding("UTF-8");

            XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (IOException e) {

            System.out.println(e.getMessage());
        }
    }


public Document readXml(String fileName) {
        File inputXml = new File(fileName);
        if (inputXml.exists()) {

            try {
                SAXReader saxReader = new SAXReader();
                FileInputStream ifile = new FileInputStream(inputXml);
                InputStreamReader ir = new InputStreamReader(ifile, "UTF-8");

                Document document = saxReader.read(ir);
                document.setXMLEncoding("UTF-8");

                return document;
            } catch (DocumentException e) {
                System.out.println(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("file is not exist");
        }

        return null;
    }

可是还是一直出错,最后终于发现了,原来刚开始测试的时候我的项目默认是GBK编码的,后来我改成了UTF-8,但是我测试程序中的中文看着没有问题,其实还是GBK的编码,只要把测试中的中文删除重写下就没问题了,这也算myeclipse中的一个小小的bug吧

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值