1.JBK编码,中文占用2字节,英文占用1字节。
2.UTF-8编码,中文占用3字节,英文占用1字节。
3.java是双字节编码,是utf-16be编码,中文占用2字节,英文也占用2字节。
当你的字节是某种编码时,这时想把你的字节编程字符串,也需要使用对应的棉麻方式,否则可能出现乱码问题。
4.文本文件就是字节序列,可以是任意编码的字节序列。如果在中文机器上创建文本文件.txt,该文件默认只认ansi编码,但它可以识别任意格式的编码文件
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class ByteTest {
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "慕课ABC";
byte[] defualtByte = s.getBytes();
System.out.println("默认编码:");
for(byte b:defualtByte)
{
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
System.out.println("\ngbk编码");
byte[] gbkByte = s.getBytes("gbk");
for(byte b:gbkByte)
{
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
System.out.println("\nutf-8编码:");
byte[] utf8Byte = s.getBytes("utf-8");
for(byte b:utf8Byte)
{
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
System.out.println("\nutf-16be编码:");
byte[] utf16Byte = s.getBytes("utf-16be");
for(byte b:utf16Byte)
{
System.out.print(Integer.toHexString(b & 0xff)+" ");
}
String strDefualt = new String(utf16Byte);
System.out.println("\n默认转换回字符串结果:"+strDefualt);
String strUtf16 = new String(utf16Byte,"utf-16be");
System.out.println("utf-16be格式转换回字符串结果:"+strUtf16);
System.out.println("java默认编码格式:"+Charset.defaultCharset());
}