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中。