关于String中各种编码中文字符的字节长度

在java中,一个英文字符在UTF-8/GBK/GB2312中是占用一个字节,在UTF-16中占用4个字节,如下测试:

先来看英文字母所占字节数:

char c = 'a';
try {
  System.out.printf("默认编码:%s, 字节数:%d%n", System.getProperty("file.encoding"), Character.toString(c).getBytes().length);
  System.out.printf("编码:%s, 字节数:%d%n", "utf8", Character.toString(c).getBytes("utf8").length);
  System.out.printf("编码:%s, 字节数:%d%n", "utf16", Character.toString(c).getBytes("utf16").length);
  System.out.printf("编码:%s, 字节数:%d%n", "gb2312", Character.toString(c).getBytes("gb2312").length);
  System.out.printf("编码:%s, 字节数:%d%n", "gbk", Character.toString(c).getBytes("gbk").length);
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}

结果如下:

默认编码:UTF-8, 字节数:1
编码:utf8, 字节数:1
编码:utf16, 字节数:4
编码:gb2312, 字节数:1
编码:gbk, 字节数:1

再来看看中文字符:

char c = '中';
try {
  System.out.printf("默认编码:%s, 字节数:%d%n", System.getProperty("file.encoding"), Character.toString(c).getBytes().length);
  System.out.printf("编码:%s, 字节数:%d%n", "utf8", Character.toString(c).getBytes("utf8").length);
  System.out.printf("编码:%s, 字节数:%d%n", "utf16", Character.toString(c).getBytes("utf16").length);
  System.out.printf("编码:%s, 字节数:%d%n", "gb2312", Character.toString(c).getBytes("gb2312").length);
  System.out.printf("编码:%s, 字节数:%d%n", "gbk", Character.toString(c).getBytes("gbk").length);
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}

结果如下:

默认编码:UTF-8, 字节数:3
编码:utf8, 字节数:3
编码:utf16, 字节数:4
编码:gb2312, 字节数:2
编码:gbk, 字节数:2

可以发现UTF-16编码下,无论中文还是字母都占用4个字节。


你可能感兴趣的:(Java基础)