字节是指一小组相邻的二进制数码。通常是8位作为一个字节。它是构成信息的一个小单位,并作为一个整体来参加操作,比字小,是构成字的单位。
在微型计算机中,通常用多少字节来表示存储器的存储容量。
编码不同,占的字节不同。
ASCII码:一个英文字母(不分大小写)占一个字节的空间,一个中文汉字占两个字节的空间。
UTF-8编码:一个英文字符等于一个字节,一个中文(含繁体)等于三个字节。中文标点占三个字节,英文标点占一个字节
Unicode编码:一个英文等于两个字节,一个中文(含繁体)等于两个字节。中文标点占两个字节,英文标点占两个字节
public static void main(String[] args) throws UnsupportedEncodingException { String s0= "中文aa"; String s1 = new String(s0.getBytes("UTF-8"),"gbk"); System.out.println(s0.getBytes().length);// 8 中文,2*3 + 2*1 System.out.println(s1.getBytes().length);// 11 System.out.println(getLength(s0));// 6 2*2+2*1 System.out.println(getLength("aaa"));// 3 } public static int getLength(String s) { int length = 0; for (int i = 0; i < s.length(); i++) { int ascii = Character.codePointAt(s, i); if (ascii >= 0 && ascii <= 255) { length++; } else { length += 2; } } return length; }
写数据
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
FileUtils.writeStringToFile(file, comment, "GBK");