通过键盘输入中文,通过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
-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
解决方案 »
- 新手提问。。。。。。。。。。大家帮帮忙,看看那里出问题了,不能运行啊(java)
- 静态方法的调用...
- 父类窗体有3个按钮,但个个子类继承过来后每个button的相应不同,请问如何做?
- 挑战Java正则表达式高手的一个难题:非一个字符串的问题?
- 请问二进制的10101010表示的byte值是多少?
- 为什么我的程序在执行时会自动退出呢
- 我学java不久,有那位能帮我看看,这个程序怎么不能正常运行!
- 请问数组在实际中的应用到底在什么地方?
- vector能不能存储整型数字
- jbuilder4+ias4.11+interbase5 ,各有什么作用,各起什么地位?
- 关于字符串数组的值的问题
- 上传war包成功,上线访问404
System.out.println(Integer.toHexString(ch)+"*****");System.in.read() 获取的是一个字节 返回的是ascii码Integer.toHexString(ch)
返回为无符号整数基数为16的整数参数的字符串
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;
} }
}}