徹底解決Java的字元編碼問題[00原創]

來源:互聯網
上載者:User
最近在做Mp3 ID3標籤的提取,又遇到了中文字元編碼的問題。
記得以前從一個文字檔中讀取中文字內容時,如下方法所示:

/**
     * 按行對去讀取文字檔內容
     * @param fileName
     *                檔案路徑與檔案名稱
     * @throws IOException
     */
    public void readFile(String fileName)
    {
    try
    {
        InputStream is = new FileInputStream(fileName);

        ByteArrayOutputStream byteout = new ByteArrayOutputStream();
        byte tmp[] = new byte[1024];
        byte context[];

        is.read(tmp);
        byteout.write(tmp);
        context = byteout.toByteArray();
        String str = new String(context, "GBK");
        System.out.println(str);
    }
    catch (FileNotFoundException fnfe)
    {
        fnfe.printStackTrace();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    }

同樣的方法處理ID3標籤是出現了問題。new String(context, "GBK");出來的還是亂碼。。。。
查閱了各種資料,寫了個簡單的解決方案測試,如下:

package cn.edu.ynu.sei.liva.test;

public class CharSetDecoder
{
    public static void main(String[] args)
    {
    try
    {
        String musicName = "Ó¸ҵÄÐÄ";
        System.out.println("Before decoding: " + musicName);
        // 1. 把musicName(按Unicode->ISO-8859-1) 轉回原來的byte[]。
        // 2. 因為原來的歌名是GBK編碼方式,所以把bytes[] 按照GBK->Unicode的方式轉碼
        String musicNameDecode = new String(musicName.getBytes("ISO-8859-1"), "GBK");
        System.out.println("After decoding:" + musicNameDecode);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    }
}

呵呵,終於可以徹底搞定Java的字元編碼問題了!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.