A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© caijunsong 中级黑马   /  2014-4-19 12:36  /  898 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 caijunsong 于 2014-4-19 12:44 编辑
  1. public static void main(String [] args) throws Exception
  2.         {
  3.                 String strChina = "中国";
  4.                 //这里放回的是length()返回的是2,两个字符串
  5.                 for(int i=0;i<strChina.length();i++)
  6.                 {
  7.                 System.out.println(Integer.toHexString((int)strChina.charAt(i)));
  8.                 }
  9.                 byte [] buf=strChina.getBytes("gb2312");
  10.                                for(int i=0;i<buf.length;i++)
  11.                 {
  12.                         System.out.println(Integer.toHexString(buf[i]));
  13.                 }
  14.                 System.out.println(strChina);
  15.         }
  16. //张老师关于编码问题说:在java中字符使用的都是unicode编码,就是所有不管中文或字母都是两个字节
  17. //但是我把上面的gbk2312改成unicode 它的length却是6.怎么解释
  18. //就是我们java程序中的中文是采用UNICODE(全球)?但是记事本却是gbk编码(本地)?
  19. //因此把一个中文文件,用记事本打开 会出现乱码??
  20. //如果自己有比较总结  请复制链接给我  谢谢!!
复制代码

2 个回复

倒序浏览
1个字节是8个二进制位,而byte就是8个二进制位,1个汉字是16位,也就是两个汉字是4个byte,然后unicode是用三个byte表示一个汉字的,自然你改成unicode编码length就是6了,如果你程序中指定了是用unicode编码,那么记事本打开的时候它会去读取存储的信息的头部,来判断是以哪种方式存储的,就用哪种方式取出
回复 使用道具 举报
1、JAVA读取文件,避免中文乱码。

  1. /**
  2.   * 读取文件内容
  3.   *
  4.   * @param filePathAndName
  5.   *            String 如 c:\\1.txt 绝对路径
  6.   * @return boolean
  7.   */
  8. public static String readFile(String filePathAndName) {
  9.   String fileContent = "";
  10.   try {  
  11.    File f = new File(filePathAndName);
  12.    if(f.isFile()&&f.exists()){
  13.     InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");
  14.     BufferedReader reader=new BufferedReader(read);
  15.     String line;
  16.     while ((line = reader.readLine()) != null) {
  17.      fileContent += line;
  18.     }   
  19.     read.close();
  20.    }
  21.   } catch (Exception e) {
  22.    System.out.println("读取文件内容操作出错");
  23.    e.printStackTrace();
  24.   }
  25.   return fileContent;
  26. }

复制代码

2、JAVA写入文件,避免中文乱码。
  1. public static void writeFile(String filePathAndName, String fileContent) {
  2.   try {
  3.    File f = new File(filePathAndName);
  4.    if (!f.exists()) {
  5.     f.createNewFile();
  6.    }
  7.    OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
  8.    BufferedWriter writer=new BufferedWriter(write);   
  9.    //PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
  10.    //PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
  11.    writer.write(fileContent);
  12.    writer.close();
  13.   } catch (Exception e) {
  14.    System.out.println("写文件内容操作出错");
  15.    e.printStackTrace();
  16.   }
  17. }

复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马