日期:2014-05-20  浏览次数:20758 次

请问存在GB2312编码的String吗?如何构造出这样的String?
手头上需要去访问Web Service的一个接口,例如: String Func(String str)。这个接口的参数要求是一个GB2312编码的String。

现在的问题是,我构造不出来这样的String。使用getBytes只能得到byte[],而不是String。


String string = "<?xml version=\"1.0\" encoding=\"GB2312\"?><root><author>中文123</author></root>";
//按照 GB2312 Encode编码得到字节
byte[] bytes = string.getBytes("GB2312");

但是bytes不能发过来得到GB2312编码的String。比如各种new String构造函数。

// 从字节按照 GB2312 Decode解码得到本Java文件相应编码格式字符串。比如本文件是UTF-8格式的,string就是UNICODE。
string = new String(bytes, "GB2312");

------解决方案--------------------
Java code

public static void main(String[] args)throws Exception {
        String str = "中国";
        byte[] buff = str.getBytes("gb2312");
        //这里的gbStr是乱码,但是内容却是gb2312编码格式的字节数组
        String gbStr = new String(buff,"ISO-8859-1");
        System.out.println(gbStr);
        //这里能正常输出“中国”
        System.out.println(new String(gbStr.getBytes("ISO-8859-1"),"gb2312"));
    }