1. 程式人生 > >IO流轉換流的字元編碼

IO流轉換流的字元編碼

    (1)字元流的出現為了方便操作字元,更重要的是加入了編碼轉換
    (2)通過子類轉換流來完成
        InputStreamReander
        OutputStreamWriter
    (3)在兩個子類物件進行構造的時候可以加入編碼表
    (4)編碼表:
        將各個國家的文字用二進位制數字表示並一一對應,形成一張表,這就是編碼表
    (5)常見的編碼表:
        **ASCII:美國標準資訊交換碼,用一個位元組的七位表示
        **ISO8859-1:拉丁碼錶,歐洲碼錶,用一個位元組的八位表示
        **GB2312:中文編碼表,用兩個位元組表示
        **GBK:中文編碼表升級,融合錄入更多的中文字元,用兩個位元組表示,為避免和老美重複
               兩位元組的最高位都是1,即漢字都是用負數表示
        **Unicode:國際標準碼,融合了多種文字,所有文字都用兩個位元組表示
        **UTF-8:用一個位元組到三個位元組表示。
        注:Unicode能識別中文,UTF-8也能識別中文,但兩種編碼表示一個漢字所用的位元組數不同
        Unicode用兩個位元組,UTF-8用三個位元組,故涉及到編碼轉換。
    (6)在流中涉及編碼表的轉換隻有轉換流:
        InputStreamReander
        OutputStreamWriter
    (7)程式碼示例:
        public static void write() throws IOException
        {
            OutputStreamWriter osw1 = new OutputStreamWriter(new FileOutputStream("gbk.txt"),"GBK");
            osw1.write("你好");
            osw1.close();

            OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("utf-8.txt"),"UTF-8");
            osw2.write("你好");
            osw2.close();
        }
        public static void read() throws IOException
        {
            InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");
            byte[] buf = new byte[1024];
            int len = isr.read(buf);
            sop(new String(buf,0,len));
        }
    (8)編碼解碼
        編碼:字串變成位元組陣列:String-->getBytes()-->byte[]()
        解碼:位元組陣列變成字串:byte[]-->new String(byte[],0,len)-->String
    (9)程式碼示例:
        public static void main(String[] args)
        {
            //編碼解碼1:預設編碼
            String str1 = "你好";
            byte[] buf1 = str1.getBytes();//預設解碼:Unicode,四個位元組

            //編碼解碼2:指定編碼
            String str2 = "你好";
            byte[] buf2 = str2.getBytes("UTF-8");//指定解碼:UTF-8,六個位元組

            
            //編碼解碼3:編碼正確解碼錯誤
            String str3 = "你好";
            byte[] buf3 = str3.getBytes("GBK");//指定編碼:GBK,四個位元組
            String str3 = new String(buf3,"ISO8859-1");//錯誤解碼

            //編碼解碼4:錯誤編碼正確解碼
            String str4 = "你好";
            byte[] buf4 = str4.getBytes("ISO8859-1");//錯誤編碼
            String str4 = new String(buf4,"GBK");//正確解碼,讀不出來

            //編碼解碼5:編碼對了,但是解碼錯誤了,怎麼辦呢?
            //此時可以將錯誤的解碼再錯編回去,載用正確編碼解碼
            String str5 = "你好";
            byte[] buf5 = str5.getBytes("GBK");//正確編碼
            String str6 = new String(buf5,"ISO8859-1");//錯誤解碼,讀不出來
            byte[] buf6 = str6.getBytes("ISO8859-1");//再錯誤編碼
            String str7 = new String(buf6,"GBK");//再正確解碼,這樣就可以讀出來了
        }