文件读取:获取部分输出

时间:2012-02-11 18:49:43

标签: java file filestream

我有以下代码从我的文件中检索数据。当我执行代码时,我知道它只给出了总线数的50%。为什么会这样?

    public static void main(String args[]) throws IOException
    {
        int count = 1;
    try {
            FileInputStream fileInput = new FileInputStream("C:/FaceProv.log");
            DataInputStream dataInput = new DataInputStream(fileInput);
            InputStreamReader inputStr = new InputStreamReader(dataInput);
            BufferedReader bufRead = new BufferedReader(inputStr);

                while(bufRead.readLine() != null)
                {
                    System.out.println("Count "+count+" : "+bufRead.readLine());
                    count++;

                }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

2 个答案:

答案 0 :(得分:6)

你正在读两行:

while(bufRead.readLine() != null) /// HERE
{
     System.out.println("Count "+count+" : "+bufRead.readLine()); // AND HERE
     count++;

}

但你只计算一次。所以你实际上是在阅读整个文件,但只计算一半的行。

将其更改为:

String line;
while((line = bufRead.readLine()) != null) {
     System.out.println("Count "+count+" : " + line);
     count++;
}

看看会发生什么。

答案 1 :(得分:4)

因为

while(bufRead.readLine() != null)

丢弃它刚读过的行。

String myLine = null;
while ((myLine = bufRead.readLine()) != null) {
    System.out.println("Count "+count+" : " + myLine);
    ...