输出是乱码,乱码原因:
1XMLWriter w=new XMLWriter(new FileOutputStream(“sss.xml”),f);
是由FileOutputStream编码,写入文件,默认使用本地编码:gb2312
但xml文档头指令<?xml version=”1.0” encoding=“utf-8”?>默认是utf-8,myeclipse打开时是按utf-8解码,就出错了!
解决,让FileOutputStream写数据时,不去参照本地编码,而是utf-8
XMLWriter()可以接受Writer,OutputStream 类型,只需查看哪个子类可以执行编码方式:
XMLWriter w=
new XMLWriter(new OutputStreamWriter(new FileOutputStream(“sss.xml”):”utf-8”),f)
此时:XMLWriter将数据交给OutputStreamWriter,OutputStreamWriter需要将字符流转化为字节流,需要查码表utf8,FileOutputStream不需要查码表,直接写,编码仍是utf8
2 OutputFormat f= OutputFormat.createPrettyPrint();
f.setEncoding(“utf-8”); 指定xml头指令编码,并将xml以utf-8编码为字节流
XMLWriter w=new XMLWriter(new FileWriter( “sss.xml”),f)
w.write();XMLWriter不会去查码表f,因为是String 直接给String ,两个都是字符流!没有编码过程xml头指令还是utf-8,不是OutputFormat指定的编码
由FileWriter去查码表,看系统默认码表gb2312
又会出错
只能是:
XMLWriter w=new XMLWriter(new FileOutputStream ( “sss.xml”),f)
w.write();XMLWriter会去查码表f,将String 字符流以gb2312编码方式转化为二进制字节给字节流,并将xml头指令为gb2312
OutputStreamWriter直接输出,不再查 |