一直以来学习中从来没有操作过中文文件,今天有个事必须要从一个文件中读取中文字符然后输出,才发现束手无策,求助下各位大侠。先贴下我的范例代码public static void main(String args[])
{
byte buffer[] = new byte[2056];
try
{
FileInputStream fileint = new FileInputStream("dchs.txt");
int bytes = fileint.read(buffer,0,2056);
String str = new String(buffer,0,0,bytes);
System.out.print(str);
}//try
catch(Exception e)
{
String err = e.toString();
System.out.println(err);
}//cathch
}//public static void main(String args[])我用 FileInputStream 这么操作 输出的中文总是乱码,英文字符正常。各位大侠给指教下。

解决方案 »

  1.   

    FileInputStream 是字节流,要想操作中文,用FileReader,或将FileInputStream 用InputStreamReader包装,再用BufferedReader缓冲一下。
      

  2.   

    在你基础上面改的,不过还是建议使用FileReader类来读文本文件下面的程序还跟文本文件的编码格式相关,你跑跑看看吧,读的文件名称 你自己改下就好public class ReadFileDemo {    public static void main(String args[])
        {
            byte buffer[] = new byte[2056];
            try
            {
                FileInputStream fileint = new FileInputStream("易中天拼三国.txt");
                int i=0;
                while(fileint.read(buffer)!=-1){
                    String str=new String(buffer);
                    System.out.println(str);
                }
            }//try
            catch(Exception e)
            {
                e.printStackTrace();
                String err = e.toString();
                System.out.println(err);
            }//cathch
        }
    }
      

  3.   

    这个好说 用FileReader。 FileReader 专门用来读取一些纯文本的。 FileInputstream 最底层的一个字节一个字节的读,适合读媒体文件比如图片视频
      

  4.   

    非要用FileInputStream读 可以用转换流 InputStreamReader 封起来 在用个BufferedReader封起来就好多了
      

  5.   

    用FileReader。 FileReader 专门用来读取一些纯文本的。 FileInputstream 最底层的一个字节一个字节的读,适合读媒体文件比如图片视频
      

  6.   

    我用下面的方法试了下能读中文。
    File file=new File("C:\\dchs.txt");
    char[] ch=new char[(int)file.length()];
    int len=0;
    FileReader fr;
    try {
    fr = new FileReader(file);
    len=fr.read(ch);
    System.out.println(new String(ch,0,len));
    } catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (IOException ex) {
    // TODO Auto-generated catch block
    ex.printStackTrace();
    }