Java基礎之字符串編碼

字符流

  創建  1.txt中寫入   '"哈"  字時     系統gbk編碼佔兩個字節  

 1.reader會默認使用系統的字符集去讀取比如gbk, 但返回時會從Unicode中去尋找這個字的 編碼返回了21704,

     因爲java只認 Unicode, 當使用  char( 21704 )  才能由 Unicode轉換爲   "哈"

 2.漢字的高字節以1開頭,所以會第一個字節直接合並第二個,就是一次讀兩個字節

 3.在讀時,返回-1,因爲已經沒有了,   如果是兩個  字母 " ab"  ,一個字母佔一個字節,並且高字節不是以1開頭,就會一個一個讀,所以              顯 示  97,98

  判斷是不是以 1開頭,  是字符流纔有的

public class test1 {
    public static void main(String[] args) throws Exception {
        URL resourceAsStream = test1.class.getResource("1.txt");
        String path = resourceAsStream.getPath();
        String decode = URLDecoder.decode(path, "utf-8");
        Reader in = new FileReader(decode);
        int read = in.read();
        System.out.println(read);        21704
        int read2 = in.read();
        System.out.println(read2);        -1
        in.close();
    }
}

字節流

  1.顯示 a b c:

 public static void main(String[] args) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\java\\Java源碼\\我的小開發maven版\\src\\main\\resources/1.txt");
        fileOutputStream.write(97);
        fileOutputStream.write(98);
        fileOutputStream.write(99);
        fileOutputStream.close();
    }

  2.顯示:  a 焍 b

 public static void main(String[] args) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\java\\Java源碼\\我的小開發maven版\\src\\main\\resources/1.txt");
        fileOutputStream.write(97);
        fileOutputStream.write(-97);
        fileOutputStream.write(98);
        fileOutputStream.write(98);
        fileOutputStream.close();
    }

  說明只要有一個負的字節就會連上後面一個字節,組成一個漢字(記事本GBK組的), java寫入 97 -97 98 98 記事本使用gbk解碼時     組成漢字,  必須兩個字節才能組成一個漢字(gbk)

    fileOutputStream.write(-200);   fileOutputStream.write(97);  顯示   8a 

   因爲下面 一個直接最大127   -200被轉換爲整數, 就像    byte b = (byte)-129; 強轉時  b 爲127

編解碼

  編碼,字符 --->碼錶--->數字             解碼,數字 --->碼錶--->漢字

   1.  -2  -1 爲Unicode 的標識,以他開頭

        byte[] bytes = s.getBytes("Unicode");
        System.out.println(Arrays.toString(bytes));  [-2, -1, 84, -56]

  2.java 以Unicode爲標準,   不足兩個字節時,會補足爲兩個   0,97

        String s = "a";
        byte[] bytes = s.getBytes("Unicode");  [-2, -1, 0, 97]

字符流查碼錶,字節流不查碼錶

        System.out.println((int)'哈');        21704
        System.out.println((char)21704);       哈

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章