在Eclipse中查看項目默認的編碼格式:
右擊項目——> Properties(屬性) ——> Resource ——> Test file encoding
例如,創建了一個項目名爲Test的項目,右擊Test,步驟如下圖:
GBK編碼格式是項目默認的編碼格式
點擊Other可以爲項目選擇其他編碼格式:
設置完成後點擊Apply,然後OK
public class Encode {
public static void main(String[] args)throws Exception{
String s="夢想";
byte[] bytes1=s.getBytes();//轉化成字節序列用的是項目默認的編碼GBK
System.out.print("默認編碼(GBK): ");
for(byte b:bytes1){
/*
* 把字節(轉換成了int)以16進制的方式顯示
* int是4個字節(32位),byte是一個字節,所以要在前面添加24個0
* 24個0並無意義,所以與0xff進行相與,只留下後8位
*/
System.out.print(Integer.toHexString(b&0xff)+" ");
}
System.out.println();
/*
* 以指定編碼格式顯示
* gbk編碼中文佔用兩個字節,英文佔用一個字節
*/
//以指定編碼格式顯示時會拋出異常,可以通過throws Exception迴避異常
byte[] bytes2=s.getBytes("gbk");
System.out.print("GBK: ");
for(byte b:bytes2){
System.out.print(Integer.toHexString(b&0xff)+" ");
}
System.out.println();
/*
*utf-8編碼中文佔用3個字節,英文佔用一個字節
*/
byte[] bytes3=s.getBytes("utf-8");
System.out.print("utf-8: ");
for(byte b:bytes3){
System.out.print(Integer.toHexString(b&0xff)+" ");
}
System.out.println();
/*
* java是雙字節編碼 :utf-16be
* utf-16be編碼 中文佔用2個字節,英文佔用2個字節
*/
byte[] bytes4=s.getBytes("utf-16be");
System.out.print("utf-16be: ");
for(byte b:bytes4){
System.out.print(Integer.toHexString(b&0xff)+" ");
}
System.out.println();
/*
* 當字節序列是某種編碼時,這個時候想把字節序列變成
* 字符串,也需要用這種編碼方式,否則會出現亂碼
*/
//bytes4是utf-16be,用項目默認的編碼轉換時會出現亂碼
String str1=new String(bytes4); //後面無參數時,表示採用項目默認編碼
System.out.println(str1);
String str2=new String(bytes4,"utf-16be");
System.out.println(str2);
}
}
運行結果:
默認編碼(GBK): c3 ce cf eb
GBK: c3 ce cf eb
utf-8: e6 a2 a6 e6 83 b3
utf-16be: 68 a6 60 f3
h?
夢想