通过键盘输入中文,通过system.in.read读取,然后通过println函数将读取到的字符打印出来,在debug时,设置eclipse->debug configuration->argument->vmargument为 
-Dfile.encoding=charset
-Dsun.io.unicode.encoding=charset
-Dsun.jnu.encoding=charset   charset分别设为"UTF-16","UTF-8"等值,不论我设置的是什么值,输出的总是一样的,比如我输入中国,输出的值永远为:
e4b8ade59bbd
代码如下:
ch = System.in.read();
System.out.println(Integer.toHexString(ch)+"*****");
请问键盘输入的编码到底是依据什么编码来的,是否可以设置?我用的系统是macOS sierra版本10.12

解决方案 »

  1.   

    ch = System.in.read();
    System.out.println(Integer.toHexString(ch)+"*****");System.in.read() 获取的是一个字节  返回的是ascii码Integer.toHexString(ch)
    返回为无符号整数基数为16的整数参数的字符串
      

  2.   

    谢谢!还有一个问题:如果我想将读入的ascii码转化为string再打印出来,如下代码:
            strinfo = new String(buf, 0 , pos, charset);
    System.out.println("print string:");
    System.out.println(strinfo);当我通过-Dfile.encoding=charset语句将环境变量的charset与new string中的charset设置为一样时,分别测试了utf-8,utf-16,iso8859-1和gb2312,其中前三种charset打印出来的是正确的中文字符,但是gb2312打印出的是乱码。然后我再将字符串的内容提取到字节数组中并打印出来,比如:
                                           buftmp = strinfo.getBytes("utf-16");
    for (int i = 0; i < buftmp.length; i++)
    {
    System.out.print(Integer.toHexString(buftmp[i])+"*");
    }
    System.out.println();
    还是以中国为例,此时打印的结果,按我的理解,应该是无论-Dfile.encoding=charset设置为什么值,打印的结果都应该是一样的,但是测试出来的结果都不一样。
    完整程序如下:
    public static void main(String []args) throws IOException //throws IOException
    { System.out.println(System.console());
    InputStreamReader a = new InputStreamReader(System.in);

    byte[] buf = new byte[1024];
    byte[] buftmp = new byte[1024];
    int pos = 0;
    int ch ;
    String strinfo;
    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, "ISO8859-1");
    System.out.println("print string:");
    System.out.println(strinfo);



    System.out.println("utf-16:");
    buftmp = strinfo.getBytes("utf-16");
    for (int i = 0; i < buftmp.length; i++)
    {
    System.out.print(Integer.toHexString(buftmp[i])+"*");
    }
    System.out.println();


    for (int i = 0; i < strinfo.length(); i++)
    {
    System.out.print(Integer.toHexString(strinfo.charAt(i))+"*");
    }   
    System.out.println();
    break;
    default:
    buf[pos++]= (byte)ch;
    break;


    } }

    }}