常用编码是GBK 和 UTF-8
一个汉字的存储
如果是GBK编码,占用2个字节
如果是UTF-8编码,占用3个字节
byte[] b1 = "汉字".getBytes("GBK");
System.out.println(Arrays.toString(b1));//[-70, -70, -41, -42]
byte[] b2 = "汉字".getBytes("UTF-8");
System.out.println(Arrays.toString(b2));//[-26, -79, -119, -27, -83, -105]
编码、解码
编码与解码一致,否则乱码
/*
编码:
byte[] getBytes():使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
byte[] getBytes(String charsetName):使用指定的字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
解码:
String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的 String
String(byte[] bytes, String charsetName):通过指定的字符集解码指定的字节数组来构造新的 String
*/
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
//定义一个字符串
String s = "中国";
//byte[] getBytes():使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
//byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67]
//byte[] getBytes(String charsetName):使用指定的字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
// byte[] bys = s.getBytes("UTF-8"); //[-28, -72, -83, -27, -101, -67]
byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
System.out.println(Arrays.toString(bys));
//String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的 String
// String ss = new String(bys);
//String(byte[] bytes, String charsetName):通过指定的字符集解码指定的字节数组来构造新的 String
// String ss = new String(bys,"UTF-8");
String ss = new String(bys,"GBK");
System.out.println(ss);
}
}