本站首页    管理页面    写新日志    退出


«September 2025»
123456
78910111213
14151617181920
21222324252627
282930


公告

戒除浮躁,读好书,交益友


我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:邢红瑞的blog
日志总数:523
评论数量:1142
留言数量:0
访问次数:9704117
建立时间:2004年12月20日




[java语言]利用javax.xml.transform.*;transform xml时候的encoding问题
原创空间,  软件技术,  电脑与网络

邢红瑞 发表于 2006/5/18 15:06:05

public static void savexmlFile(ConfigData cd, String Filename) {  try {    FileOutputStream fos = new FileOutputStream(new File(Filename));    TransformerFactory tFactory = TransformerFactory.newInstance();   Transformer transformer = tFactory.newTransformer();    DOMSource source = new DOMSource(cd.getDom());   StreamResult result = new StreamResult(fos);   Properties properties = transformer.getOutputProperties();   // 这里设置输出为XML格式,实际上这是XSLT引擎的默认输出格式   properties.setProperty(OutputKeys.METHOD, "xml");   /* 设置缩紧 */   properties.setProperty(OutputKeys.INDENT, "yes");   transformer.setOutputProperties(properties);   transformer.transform(source, result);  } catch (TransformerException e) {   e.printStackTrace(); // To change body of catch statement use   // File | Settings | File Templates.  } catch (FileNotFoundException e) {   e.printStackTrace(); // To change body of catch statement use   // File | Settings | File Templates.  } }      由于DOM 没有任何编码,encoding里面指定了编码方式,生成的xml文件编码方式却变成了utf-8,java内部作了处理,默认就是utf-8,它会将你的字符编码自动转为utf-8.读取时,不要使用FileReader ,因为它会默认使用GBK读取文件,应该使用InputStreamReader,使用UTF-8. public static ConfigData readConfigFile(String FileName) {   try {   File readfile = new File(FileName);   if (readfile.exists()) {    InputStreamReader fr = new InputStreamReader(      new FileInputStream(FileName),"UTF-8");    BufferedReader br = new BufferedReader(fr);    String s;    StringBuffer sb = new StringBuffer();    while ((s = br.readLine()) != null) {     sb.append(s + "\n");    }    /*     * 没有使用xml的inputsource,只好自己转码 String xmlstr=new     * String(sb.toString().getBytes("GBK"),"UTF-8");     */    log.info("readConfigFile" + sb.toString());    ConfigData cd = Xml2Dom.getConfigData(sb.toString());    br.close();    fr.close();    return cd;   } else {    return null;   }   } catch (FileNotFoundException e) {   e.printStackTrace();   /* 文件不存在,返回null */   return null;  } catch (IOException e) {   e.printStackTrace();   return null;  }  }


阅读全文(3018) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.047 second(s), page refreshed 144776281 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号