在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