网站首页 新闻首页 网页设计图形动画软件编程网站开发办公软件操作系统数据库网络技术认证考试范文资料黑客攻防 书籍教程 进入论坛

关于java中字符编码的一点心得,可能对初学者有点帮助

http://www.diybl.com/ 2007-2-6  网络 点击:  [ 评论 ]
文章搜索:    【点击打包该文章】

这是张孝祥老师的java就业培训视频教程里面的一道题目(有所变动):
编写下面的程序代码,分析和观察程序的运行结果:

import java.io.*;
public class TestCodeIO {
      public static void main(String[] args) throws Exception{
            InputStreamReader isr = new InputStreamReader(System.in,"iso8859-1");
            BufferedReader br = new BufferedReader (isr);
            String strLine = br.readLine();
            br.close();
            isr.close();
            System.out.println(strLine);
      } 
}
运行程序后,输入“中国”两个字,输出结果为 ???ú
请按照下面两种方法修改上述程序,是输入的中文能够正常输出
1。修改程序中的语句
              InputStreamReader isr = new InputStreamReader(System.in,"iso8859-1");
2。不修改上面的语句,修改下面的语句
              System.out.println(strLine);


第一种该法很简单,只要改成下面这样就可以了,这里不详细讨论
            InputStreamReader isr = new InputStreamReader(System.in,"gb2312");


这里我要详细讨论的是第二种该法怎么改

起初我是这样改的
          System.out.println(new String (strLine.getBytes(),"iso8859-1"));
输入“中国”后输出的结果虽然不是上面所述的乱码,但是还是乱码,显然这种该法是不正确的!

这里我要感谢 软件民工  告诉我的正确改法,使我恍然大悟
           System.out.println(new String (strLine.getBytes("iso8859-1")));

这两种改法究竟有什么区别呢?为了方便大家阅读,我先把正确和错误的改法帖出来:
import java.io.*;
     public class TestCodeIO {
           public static void main(String[] args) throws Exception{
                 InputStreamReader isr = new InputStreamReader(System.in,"iso8859-1");
                       //Create an InputStreamReader that uses the given charset decoder
                 BufferedReader br = new BufferedReader (isr);
                 String strLine = br.readLine();
                 br.close();
                 isr.close();
                 System.out.println(strLine);
                 System.out.println(new String (strLine.getBytes(),"iso8859-1"));//错误改法
                       //Encodes this String (strLine) into a sequence of bytes using the platform’s 
                       //default charset(gb2312) then constructs a new String by decoding the 
                      //specified array of bytes using the specified charset (iso8859-1)
                      //because this String (strLine) uses the charset decoder "iso8859-1",so it can
                      //only be encoded by "iso8859-1",cann’t be encoded by the platform’s default
                      //charset "gb2312",so this line is wrong.
                System.out.println(new String (strLine.getBytes("iso8859-1")));//正确改法
                     //Encodes this String (strLine) into a sequence of bytes using the named 
   &nb

欢迎光临DIY部落,点击这里查看更多文章教程   【点击打包该文章】
[1] [2]
如果图片或页面不能正常显示请点击这里 站内搜索:   
上一篇文章:Hibernate学习手记(一)
下一篇文章:用Java编写ASP组件

文章评论

请您留言

 

最新新闻