import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/*
编码:
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[] 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 ss = new String(bys);
String ss = new String(bys,"GBK");
//使用那种编码就要使用那种解码否则会出现乱码
System.out.println(ss);
}
}
字符串的编码解码问题
最新推荐文章于 2022-07-13 21:38:43 发布