在JAVA中对字符集编码操作的一点问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 22:24:59
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"

首先明确一点的就是:file.encoding到底改变的是什么的编码?
我们利用System.setProperties(用get也行)设置编码的时候是给jvm设置编码的,而不是给console设置(console编码的设置与本地操作系统有关)。所以当我们在console中打入中文的时候,由于本地系统仍然为中文编码(除非你在没有中文环境的Linux系统下面),所以console仍然能显示出中文,所以不应为乱码(出现乱码说明你的系统不支持中文)。
其次,为什么字符串转化的时候出现"???"的情况。注意你这里面写的程序:
strInfo = new String(buf,0,pos);
这里你已经把buf进行了一次String转换,这里虽然Jvm在内部不能认识这个中文,但是不管是英文还是中文,存储的东西都是bytes,只不过在输出的时候进行了一次编码转换(就好像我们单独看二进制程序看不懂,但是如果反编译为汇编,我们就能看懂了)。这样在第一次转换的时候strInfo就已经用本地(注意,不是Jvm)编码进行了存储(在user.language=zh这里就已经设置了默认编码为GB2312),这样的话如果此时强制转化为"ISO-8859-1"就会出现乱码,这样在进行其他转换也是没有意义的。
需要说明的是,String这个类是比较特殊的,这个类一般情况下是不受JVM环境影响的,
还有一些小问题:在case中是可以定义变量的。
上面的代码经过我的修改后可以在Eclipse 3.3M1中正常运行,包括一些Case中定义变量的情况。