Java_IO_预备基础5_编码与解码

本文详细探讨了不同字符集(如GBK、UTF-16LE、UTF8、ISO-8859-1、Unicode和ASCII)在Java中对字符串进行编码和解码的过程。通过对比各种字符集下汉字和英文数字的字节占用情况,揭示了它们的特点及适用场景。
package cn.io;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class EncodeDecode {

	public static void main(String[] args) throws IOException {
		String msg1 = "我爱你";
		String msg2 = "ILOVEYOU";

		// ENCODE
		// 默认使用工程的字符集GBK
		byte[] datas1 = msg1.getBytes();
		byte[] datas2 = msg2.getBytes();
		System.out.println("GBK每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "GBK");
		msg2 = new String(datas2, 0, datas2.length, "GBK");
		System.out.println(msg1 + msg2);

		// 使用其他字符集编码
		// UTF-16LE
		datas1 = msg1.getBytes("UTF-16LE");
		datas2 = msg2.getBytes("UTF-16LE");
		System.out.println("UTF-16LE每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "UTF-16LE");
		msg2 = new String(datas2, 0, datas2.length, "UTF-16LE");
		System.out.println(msg1 + msg2);

		// UTF8
		datas1 = msg1.getBytes("UTF8");
		datas2 = msg2.getBytes("UTF8");
		System.out.println("UTF8每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "UTF8");
		msg2 = new String(datas2, 0, datas2.length, "UTF8");
		System.out.println(msg1 + msg2);

		// ISO-8859-1 (解码中文有问题)
		datas1 = msg1.getBytes("ISO-8859-1");
		datas2 = msg2.getBytes("ISO-8859-1");
		System.out.println("ISO-8859-1每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "ISO-8859-1");
		msg2 = new String(datas2, 0, datas2.length, "ISO-8859-1");
		System.out.println(msg1 + msg2);

		// Unicode(解码中文有问题)
		datas1 = msg1.getBytes("Unicode");
		datas2 = msg2.getBytes("Unicode");
		System.out.println("Unicode每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "Unicode");
		msg2 = new String(datas2, 0, datas2.length, "Unicode");
		System.out.println(msg1 + msg2);

		// ASCII(解码中文有问题)
		datas1 = msg1.getBytes("ASCII");
		datas2 = msg2.getBytes("ASCII");
		System.out.println("ASCII每个汉字" + datas1.length / 3 + "字节&&英文数字" + datas2.length / 8 + "字节");
		// DECODE
		msg1 = new String(datas1, 0, datas1.length, "ASCII");
		msg2 = new String(datas2, 0, datas2.length, "ASCII");
		System.out.println(msg1 + msg2);

		// 乱码的情况
		// 1.字节数不够
		// 2.字符集不统一
	}
}

控制台输出
在这里插入图片描述
以下3种字符集不支持汉字
在这里插入图片描述
备注

//字符串转字节数组
byte[] datas1 = msg1.getBytes();
//字节数组转字符串
msg1 = new String(datas1, 0, datas1.length, "GBK");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值