import java.util.*;
import java.nio.charset.*;
class CharsetTest
{
public static void main(String[] args) throws Exception
{
/*Map m=Charset.availableCharsets();
Set names=m.keySet();
Iterator it=names.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}*/
Properties pps=System.getProperties();
//pps.list(System.out);
pps.put("file.encoding","ISO-8859-1");
int data;
byte[] buf=new byte[100];
int i=0;
while((data=System.in.read())!='q')
{
buf[i]=(byte)data;
i++;
}
String str=new String(buf,0,i);
//System.out.println(str);
String strGBK=new String(str.getBytes("ISO-8859-1"),"GBK");
System.out.println(strGBK);
}
}
我运行的时候输入“测试q”然后回车,居然出来一些问号,为什么啊?

解决方案 »

  1.   

    首先楼主应该是打算改变 JVM的字符集编码。
    不过这样是失败的。因为jvm的字符集配置是在jvm启动的时候就加载的,在程序里设置是无效的。
    应该在启动jvm参数配置上加 -Dfile.encoding=ISO-8859-1
    这样JVM的默认字符集编码就是ISO-8859-1了。不过这样运行还是??? ,不用担心此时字符串是通过GBK写入console的。 现在console的显示字符编码已经是ISO-8859-1了,所以乱码正常。
    可以将byte写到文件查看。
      

  2.   

    这个程序对于jdk 1.4.1是有效的,以后的版本,设置file.encoding就无效了