国产毛片午夜福利,国产黄网,国产亚洲天堂,97国产精品

  •  
    使用FileWriter可以寫UTF-8的解決方法
    發(fā)布時間:2008-05-08   瀏覽次數(shù):1183409

    使用FileWriter可以寫UTF-8的解決方法

    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。
     * 所以要創(chuàng)建一個utf-8的文件,用FileWriter是不行的。
     * 目前不知道如何更改其用來寫文件的編碼方式,因此對于創(chuàng)建utf-8文件使用如下方式來代替。
     *
     * 參見:
     * http://www.malcolmhardie.com/weblogs/angus/04/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();
            }
        }
    }

    立即預(yù)約