2012-02-11 83 views
1

我有以下代碼來從我的文件中檢索數據。當我執行代碼時,我知道它只給出總線上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(); 
     } 
    } 
+1

修復將字符串行; while((line = bufRead.readLine())!= null),刪除第二條readline。 – 2012-02-11 18:55:32

回答

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++; 
} 

,看看會發生什麼。

+0

是的,你是對的。謝謝。但是我在控制檯中得到了一些空行。例如:在輸入行中,總數爲100,我得到120或125行。 – Arung 2012-02-11 19:14:02

+0

@Mayilarun你確定嗎?使用您向我們顯示的代碼幾乎是不可能的。 – soulcheck 2012-02-11 19:17:49

+0

@Mayilarun可能檢查文件的編碼和/或是否有一些虛假的cr-lf在行末 – soulcheck 2012-02-11 19:19:27

4

因爲

while(bufRead.readLine() != null) 

丟棄行只是閱讀。

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