Java字符串編碼一些知識總結:
package com.dcz.io;
import java.io.UnsupportedEncodingException;
public class EncodeDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "中國ABC";
// 轉換成字節數組是項目默認的編碼GBK
byte[] byteArray = str.getBytes();
for(byte b : byteArray){
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
System.out.println();
// 顯示轉換爲GBK編碼
byte[] byteArray2 = str.getBytes("gbk");
for(byte b: byteArray2){
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
System.out.println();
// 顯示轉換爲UTF-8編碼(在UTF-8編碼中,中文佔用3個字節,英文佔用一個字節)
byte[] byteArray3 = str.getBytes("utf-8");
for(byte b : byteArray3){
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
System.out.println();
// 顯示轉換爲UTF-16be(在此編碼上,中文和英文各站兩個字節)
byte[] byteArray4 = str.getBytes("utf-16be");
for(byte b : byteArray4){
System.out.print(Integer.toHexString(b & 0xff) + " ");
}
/**
* 當你的字節序列是某種編碼時候,想把字節序列變成字符串也需要使用某種編碼,否則亂碼。
*/
System.out.println();
// 亂碼原因是由於轉換和反轉編碼不統一
String str1 = new String(byteArray3);
System.out.println(str1);
// 不亂碼原因是由於轉換和反轉使用了統一格式編碼
String str2 = new String(byteArray3, "utf-8");
System.out.println(str2);
}
}
總結:從上面的測試代碼中可以瞭解到字符亂碼是和字符編碼有直接關係。