RSS
热门关键字:  java  Ajax  JSP  JSF  Struts
当前位置 : 首页>Java>列表

使用FileWriter可以写UTF-8的解决方法

来源: 作者: 时间:2007-10-15 点击:

FileWriter不能写utf-8,相信好呢多新手都遇到过吧,今天我们就来解决这个问题,看下面的例子。

 

 

package cn.yethyeth.sample.io; 

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.UnsupportedEncodingException; 

/** *//** 
 * 本文件名为FileWriterSubstituteSample,实际上是在寻找FileWriter的替代者。 
 * 因为FileWriter在写文件的时候,其编码方式似乎是System.encoding或者System.file.encoding, 
 * 在中文win下encoding基本是gb2312,在en的win下基本是iso-8859-1,总之不是utf-8。 
 * 所以要创建一个utf-8的文件,用FileWriter是不行的。 
 * 目前不知道如何更改其用来写文件的编码方式,因此对于创建utf-8文件使用如下方式来代替。 
 * 
 * 参见: 
 * http://www.malcolmhardie.com/weblogs/angus/2004/10/23/java-filewriter-xml-and-utf-8/ 
 */ 
public class FileWriterSubstituteSample ...{ 
    public static void main(String[] args)...{ 
        String path="cn/yethyeth/sample/resources/XML_UTF-8.xml"; 
        try ...{ 
            OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(path),"UTF-8"); 
            out.write("<?xml version="1.0" encoding="utf-8"?><a>这是测试。</a>"); 
            out.flush(); 
            out.close(); 
            System.out.println("success..."); 
        } catch (UnsupportedEncodingException e) ...{ 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (FileNotFoundException e) ...{ 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
  } catch (IOException e) ...{ 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
    } 
}

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
Google Adsense
相关文章