« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
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; }
} |
|
|