使用实例化一个string对象在构造函数里填入byte数组的方式结果是乱码,多填一个utf—8的参数结果也是乱码,请问应该怎么让byte数组转换成string字符串
你是这样转换的么?
new String("张三".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)
首先你要确定你的byte[]数组里面的数据是什么编码。我写了一个测试函数,希望能说清楚:
public void test() throws Exception {
final String TEST = "测试";
byte[] aaa = TEST.getBytes("GBK");
byte[] bbb = TEST.getBytes("UTF-8");
System.out.println("编码正确:" + new String(aaa,"GBK"));
System.out.println("编码正确:" + new String(bbb,"UTF-8"));
System.out.println("编码错误:" + new String(aaa,"UTF-8")); //本来是GBK编码,这里用utf-8来创建。乱码
System.out.println("编码错误:" + new String(bbb,"GBK")); //本来是utf-8编码,这里用GBK来创建。乱码
}
不知道你这个问题是否已经解决, 如果还没有解决的话: