java 字符类型 字节数_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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值