字符串中的编码解码问题
-
编码:
byte[] getBytes();使用平台的默认字符集将该String编码为一系列字节,将结果存储到新的字节数组中
byte[] getBytes(String characterName);使用指定的字符集将该String编码为一系列字节,将结果存储到新的字节数组中 -
解码
String(byte[] bytes):通过使用平台的默认字符集解码指定字节数组来构造新的String
String(byte[] bytes,String characterName):通过使用平台的指定字符集解码指定的字节数组来构造新的String -
汉字的存储:
如果是GBK编码是2个字节
如果是UTF-8编码,占用3个字节
以图文和代码形式讲解
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
//编码
byte[] bytes = "菜徐琨".getBytes();//默认UTF-8编码
System.out.println(Arrays.toString(bytes));//[-24, -113, -100, -27, -66, -112, -25, -112, -88]
byte[] bytes1 = "菜徐琨篮球".getBytes("GBK");
System.out.println(Arrays.toString(bytes1));//[-78, -53, -48, -20, -25, -5]
//解码
String s = new String(bytes);
System.out.println(s);
String gbk = new String(bytes1, "GBK");
System.out.println(gbk);
}
}
图文:
2.
package Demo;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
//编码
byte[] bytes1 = "菜徐琨篮球".getBytes("GBK");
System.out.println(Arrays.toString(bytes1));//[-78, -53, -48, -20, -25, -5]
//解码
String gbk = new String(bytes1, "UTF-8");
System.out.println(gbk);
}
}
图文: