FileInputStream读取文件不能读取全部内容

最近在学习java的输入流,用FileInputStream读取文件不能读取全部内容,都去的文件如下图:


注意:文件只有3行!!!!

读取的文件



在myeclipse中的输入如下图:

注意:输出只有2行!!!!

输出




实在找不出哪里错了,还请不吝赐教,非常感谢!

代码如下:


package firPrj;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileReaderClass {
    public static void main(String []args){
        FileReaderClass fileReader = new FileReaderClass();

        System.out.println("readByByte:");
        fileReader.readByByte("c:\\file.txt");
    }

    private void readByByte(String fileName){
        InputStream in = null;
        try{
            in = new FileInputStream(fileName);

            int tem = -1;
            while((tem = in.read()) != -1){
                System.out.write(tem);
            }
        } catch(IOException e){
            e.printStackTrace();
        } finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

楼主。。你输出的时候用的是System.out.write()方法,write()方法和print()方法的区别是一个输出字符流,一个输出字节流。
字符流有缓冲,即会把内容缓冲在内存中,只有flush()的时候才输出。
所以你在while循环后面加个System.out.flush();即可全部输出了。。
你可能会问为什么前面两行会输出,这就要看write()的源码了,你会发现 if ((b == '\n') && autoFlush){out.flush();}
至此真相大白了吧。。前两行后面有换行所以会自动flush()

/** //*读文件 * @param path * @return * @throws IOException */ public String FileInputStreamDemo(String path) throws IOException...{       File file=new File(path);  ......
答案就在这里:FileInputStream读取文件
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。

我运行了一下,发现代码没有问题

不要用System.out.write(tem)打印到控制台,Debug下看到tem已经读到了第三行的字符,但是因为write方法是将指定的字符写入缓冲中,在这行代码下加入System.out.flush();可以在控制台上打印出来第三行的字符;或者不用System.out.write(tem),用System.out.printf("%c",tem);这条方法也可以将文件中的全部字符打印到控制台