以下三段程序,为什么(1)读中文不会乱码,(2)会乱码,(3)也会乱码,主要是想问(1)为什么不会,他不也是每次读一个字节吗?(1)
import java.io.File;
 import java.io.InputStream;
 import java.io.FileInputStream;
 public class InputStreamDemo04
 {
  public static void main(String[] args) throws Exception
  {
  InputStream in =null;
  in =new FileInputStream(new File("f:"+File.separator+"text.txt"));
  int temp=0;
  int len=0;
  byte[] b =new byte[1024];
  while((temp=in.read())!=-1)
  {
  b[len]=(byte)temp;
  len++;
 
  }
  in.close();
  System.out.println("长度:"+len);
  System.out.println("输入的内容是:"+new String(b,0,len));
  }
 }
===============================================================
(2)
import java.io.File;
 import java.io.InputStream;
 import java.io.FileInputStream;
 public class InputStreamDemo05
 {
  public static void main(String[] args) throws Exception
  {
  InputStream in =null;
  in =new FileInputStream(new File("f:"+File.separator+"text.txt"));
  StringBuffer s =new StringBuffer();
  int temp=0;
  int len=0;
  while((temp=in.read())!=-1)
  {
  char c =(char)temp;
  s.append(c);
 
  }
  in.close();
  System.out.println("输入的内容是:"+s);
  }
 }
==============================================
(3)
import java.io.*;
 public class InputStreamDemo06
 {
  public static void main(String[] args) throws Exception
  {
  File f =new File("f:"+File.separator+"text.txt");
  InputStream in =null;
  in =new FileInputStream(f);
  byte[] b =new byte[4];
  int hasRead=0;
  while((hasRead=in.read(b))>0)
  {
  System.out.println("长度是:"+hasRead);
  System.out.println(new String(b,0,hasRead));
  }
  }
 }

解决方案 »

  1.   

    (1) byte[] b =new byte[1024];
    (2)byte[] b =new byte[4];
    兄弟,(1)和(2)其实都会有乱码的:
        一个汉字是2个字节,(2)每次可以读出的是2个完整的汉子,
    如果你要读出的内容全是汉子字符也是汉子格式的,那么不会有乱码出现
    如果你所读的内容中有汉字和偶数个字母,并且字母都在一起,那么也不会有乱码
        这样说起来,(1)肯定会有乱码的,其一次可以完整的读出512个汉字,要是你读是内容是:
    a汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字汉字...(省略号后面全是汉字,并且是在一行,那么肯定会有乱码的)
        
      

  2.   

    有Reader在,为什么要用InputStream读文本文件呢..
      

  3.   

    文本文件请使用 Reader。一个汉字多少字节和你选择了什么编码有关。