Java,String,UTF-8, GBK

本文详细介绍了如何在Java中进行字符编码的转换,包括从UTF-8到GBK以及其他编码之间的转换方法,并通过具体代码示例展示了如何操作字符串和字节数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 代码及解析:

String strUtf8 = "abc123测试";    //utf8字符串
byte [] strGbkBytes = strUtf8.getBytes("GBK");    //获取GBK格式的数组
System.out.println("GBK  bytes: " + Arrays.toString(strGbkBytes));
byte [] strUtf8Bytes = strUtf8.getBytes("UTF-8");    //获取UTF8格式的数组
System.out.println("UTF8 bytes: " + Arrays.toString(strUtf8Bytes));
//文字和编码一致
String strGbk = new String(strGbkBytes, "GBK");    //告诉String,strGbkBytes的数据时GBK格式
byte [] strGbkBytes1 = strGbk.getBytes("GBK");  //获取GBK格式的数组
System.out.println("GBK1 bytes: " + Arrays.toString(strGbkBytes1));
//文字和编码不一致
String strGbk2 = new String(strGbkBytes, "UTF-8"); //告诉String,strGbkBytes的数据时UTF-8格式
byte [] strGbkBytes2 = strGbk2.getBytes("GBK"); //获取GBK格式的数组
System.out.println("GBK2 bytes: " + Arrays.toString(strGbkBytes2));

2. 文件为UTF-8格式存储时,其中的汉字编码也为UTF-8

比如:String strTest = "abc123测试"; //在UTF-8文件中,“测试”直接编码为UTF-8格式

3. 获取特定格式的字符数组

String strTest = "abc123测试";     //假设文件格式为UTF-8

//strTest中以UTF-8格式存储“测试”,getBytes的参数指明需要转换为何种类型的数组

byte [] testBytesGbk = strTest.getBytes("GBK");    //获取GBK格式的数组

byte[] testBytesUtf8 = strTest.getBytes("UTF-8");  //获取UTF-8格式的数组

注意:在UTF-8文件中,不存在非UTF-8格式的String,只存在非UTF-8格式的数组。

4. 根据数组中的数据生成String

byte [] bytesData = {.........};

String strBytes = new String(bytesData, "GBK");  //告知String,传递给他的bytesData中存放的是GBK编码的字符,String会自动转换为UTF-8并存储在strBytes中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值