java中各种数据类型占用字节数
1字节(Byte)=8bit
java的基本类型
| 类型 | 所占字节 |
| byte | 1 |
| short | 2 |
| int | 4 |
| long | 8 |
| float | 4 |
| double | 8 |
| char | 2 |
String中字母和汉字所占字符是不一样的,并且与编码有关
英文字母:A
| 字节数 | 编码 |
| 1 | GB2312 |
| 1 | GBK |
| 1 | GB18030 |
| 1 | ISO-8859-1 |
| 1 | UTF-8 |
| 4 | UTF-16 |
| 2 | UTF-16BE |
| 2 | UTF-16-LE |
中文汉字:我
| 字节数 | 编码 |
| 1 | GB2312 |
| 2 | GBK |
| 2 | GB18030 |
| 1 | ISO-8859-1 |
| 3 | UTF-8 |
| 4 | UTF-16 |
| 2 | UTF-16BE |
| 2 | UTF-16-LE |
附录:计算String字节数的代码
package com.dingrui.stringbytelength;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.dozer.loader.api.FieldDefinition;
public class StringByteLength {
/*
* GB2312 GBK GB18030 ISO-8859-1 UTF-8 UTF-16 UTF-16BE UTF-16LE
*/
public static void main(String[] args) throws IOException {
String s1 = "a";
String s2 = "龘";
System.out.println(s1 + " GB2312 " + s1.getBytes("GB2312").length);
System.out.println(s1 + " GBK " + s1.getBytes("GBK").length);
System.out.println(s1 + " GB18030 " + s1.getBytes("GB18030").length);
System.out.println(s1 + " ISO-8859-1 " + s1.getBytes("ISO-8859-1").length);
System.out.println(s1 + " UTF-8 " + s1.getBytes("UTF-8").length);
System.out.println(s1 + " UTF-16 " + s1.getBytes("UTF-16").length);
System.out.println(s1 + " UTF-16BE " + s1.getBytes("UTF-16BE").length);
System.out.println(s1 + " UTF-16LE " + s1.getBytes("UTF-16LE").length);
System.out.println("---------------");
System.out.println(s2 + " GB2312 " + s2.getBytes("GB2312").length);
System.out.println(s2 + " GBK " + s2.getBytes("GBK").length);
System.out.println(s2 + " GB18030 " + s2.getBytes("GB18030").length);
System.out.println(s2 + " ISO-8859-1 " + s2.getBytes("ISO-8859-1").length);
System.out.println(s2 + " UTF-8 " + s2.getBytes("UTF-8").length);
System.out.println(s2 + " UTF-16 " + s2.getBytes("UTF-16").length);
System.out.println(s2 + " UTF-16BE " + s2.getBytes("UTF-16BE").length);
System.out.println(s2 + " UTF-16LE " + s2.getBytes("UTF-16LE").length);
}
/**
* 将转码后的文字写入文件,通过编辑器打开测试,确认写入的是相应编码
*
* @param bytes
* @throws IOException
*/
public void writeFile(byte[] bytes) throws IOException {
String path = StringByteLength.class.getResource("/").getPath();
System.out.println(path);
String file_path = path + "charsetFile";
File file = new File(file_path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
}
}

浙公网安备 33010602011771号