岗日加古:JAVA中怎样改变本地字符集编码

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/29 02:46:40
public class CharDecode {

public static void main(String[] args) throws Exception
{
// TODO: Add your code here
//System.getProperties().list(System.out);
System.getProperties().put("file.encoding","ISO-8859-1");//为什么改变字符集编码,没作用
System.getProperties().list(System.out);
System.out.println("please enter a chinese word:");
byte [] buf = new byte[1024];
int pos = 0;
String strInfo = null;
int ch = 0;
while(true)
{

ch = System.in.read();
System.out.println(Integer.toHexString(ch));
switch(ch)
{
case '\r':
break;
case '\n':
strInfo = new String(buf,0,pos);//在case里不能定义变量
for(int i=0;i<strInfo.length();i++)
{
System.out.println(Integer.toHexString(
/*(int)*/strInfo.charAt(i)));
}
System.out.println(new String(strInfo.getBytes("ISO-8859-1"),"gb2312"));
//System.out.println(strInfo);
break;
default:
buf[pos++] = (byte)ch;
}
}
}
}
运行程序,确实显示file encoding:ISO-8859-1,说明本地字符集编码确实改变了,但当你输入System.out.println(strInfo);是依然能正确打印中文字符,应该是乱码才对啊。因为本地字符集编码已经不是GB2312了啊。
而且当你输入System.out.println(new String(strInfo.getBytes("ISO-8859-1"),"gb2312"));时,本想通过逆转换成字节数组,再同过GB2312转换成Unicode码,正确显示中文时,打印的却是“??”问号(我输入的是“中国”二字),不知道是哪里有问题?
是不是和自己电脑的某些设置有关啊,好心人如果在你的电脑上也是这个问题,那就还是代码的问题了,如果没问题,那就是我电脑上的问题了。

System.out.println(new String(strInfo.getBytes("ISO-8859-1"),"gb2312")); 你在输出的时候这么转码,还会输出乱码,见鬼了