首先我使用的開發環境是Eclipse.創建一個Java Project默認的編碼則為GBK,如圖:
下面便是具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import java.io.UnsupportedEncodingException; public class Demo1 { public static void main(String[] args) throws UnsupportedEncodingException { String s = "我愛ABC" ; byte [] bytes1 = s.getBytes( "gbk" ); //不寫編碼,則使用平臺的默認字符集將此 String 編碼為 byte序列,并返回byte[]. //s.getBytes(Charset charset) 使用給定的charset將此String編碼到byte序列; //返回的是一個byte[]字節數組 for ( byte b: bytes1){ System.out.print(Integer.toHexString(b& 0xff )+ " " ); //Integer.toHexString(int i)以十六進制(基數 16)無符號整數形式返回一個整數參數的字符串表示形式 } //gbk編碼中文占有兩個字節,英文占有一個字節 System.out.println(); byte [] bytes2 = s.getBytes( "utf-8" ); for ( byte b: bytes2){ System.out.print(Integer.toHexString(b& 0xff )+ " " ); } //utf-8編碼 中文占有三個字節,英文占有一個字節 System.out.println(); //java是雙字節編碼 --->utf-16be >> 中文和英文都占有兩個字節 byte [] bytes3 = s.getBytes( "utf-16be" ); for ( byte b: bytes3){ System.out.print(Integer.toHexString(b& 0xff )+ " " ); } /*當你的字節序列是某種編碼時,這個時候想把字節序列變成 *字符串,也需要用這種編碼方式,否則會出現亂碼 * */ System.out.println(); String str1 = new String(bytes3);//用項目默認的編碼即(GBK編碼) ----->> bytes3在上面定義成“utf-16be”的編碼了,所以會出現亂碼 System.out.println(str1); System.out.println(); String str2 = new String(bytes3,"utf-16be"); System.out.println(str2); /* * 文本文件就是字節序列 * 可以是任意編碼的字節序列 * 如果我們在中文機器上直接創建文本文件,那么該文本文件只認識ansi編碼 * */ } } |
打印的結果:
總的來說,編碼必須對應,不然會出現亂碼。