/*
假设有A,B两种字符编码方式,如果buf中数据是以A编码来存储的,
则调用
String strChina = new String(buf, B)
结果会怎样,会得到什么样的字符串, str在内存中的二进制数据到底是什么

String strChina = new String(strInfo.getBytes("iso8859-1"), "gb2312");
如果strInfo本身是以iso8859-1存储的,那strInfo.getBytes("iso8859-1")
返回的肯定是iso8859-1编码下的二进制数据,它怎么可能转化成gb2312
这实际上还是第一个问题,第一个问题解决了,这个问题自然而然也就解决了!
*/
import java.io.*;
public class CharDecoder
{
public static void main(String [] args) throws Exception
{
System.out.println("please enter a Chinese String");
byte [] buf=new byte[1024];
int ch=0;
int pos=0;
String strInfo=null;

while(true)
{            
ch =System.in.read(); //从键盘上每次读取一个字节
System.out.println(Integer.toHexString(ch)); //将读取的字节转化为十六进制数据,由输出结果来看,键盘输入时的确是按照gb2312来输入的

switch(ch)
{
case '\r':
break;

case '\n':
try
{
strInfo= new String(buf,0,pos, "unicode"); //把"iso8859-1" 改为"Unicode" "UTF-8"输出结果完全不一样,很难理解,感觉张孝祥书上277页很多地方说的都不对
}
catch (UnsupportedEncodingException e)
{
System.out.println("编码出错!");
System.exit(-1);
}

System.out.println("strInfo字符串对象中每个字符的十六进制值是:");
for(int i=0;i<strInfo.length();i++)  //27行
{
System.out.println("i -> " + Integer.toHexString
((int)strInfo.charAt(i)));
} //31行
System.out.println("strInfo = " + strInfo);
String strChina = new String(strInfo.getBytes("unicode"), "gb2312");
System.out.println("strChina = " + strChina);

System.out.println("直接调用System.out.write()的输出结果是:");
for(int i=0;i<pos;i++)
System.out.write(buf[i]);
System.out.println();//想想为什么要这一句
return;

default:
buf[pos++]=(byte)ch;
}
}
}
}

解决方案 »

  1.   

    System.in.read();// 这里应该是按照你的系统默认编码获取的字节,也就是gb2312
             最后得到buf[]其实就是将你输入的字符串按照gb2312的规则编码成了一个字节数组
             你只有按照gb2312的规则把buf[]还原成字符串
             如果new String(buf,0,pos, "unicode")这里的方式和前面不一样,就会出现乱码
      

  2.   

    楼主,我说一样哈,就是JAVA UNICODE可以和任何编码之间映射,所以你可以转成UNICODE后再转GBK,以前我用GBK转UTF-8就是这样弄的,你可以试试.