2017-08-17 13 views
0

嗨StackOverflow的人,讀線是不相符的

我有這個問題在我的系統,在那裏我有一個文本文件 線記錄的發展,我正在使用BufferedReader拆分每行按管道檢索(|)。我正在使用Quartz來每天運行這個文件的讀取。當我測試它時,我每分鐘都會設置一次石英工作,以便我可以在每分鐘實際讀取文件的情況下測試它。它通過使用它來檢查文本文件中的所有行。

BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream)); 
String line = null; 
int counter = 0; 
while((line = reader.readLine()) != null){ 
    counter++; 
} 
System.out.println(counter); 

但是,當我分裂String,檢索4451記錄的結果是不一致的。有時候,它只能檢索1000+到2000+的記錄,有時它會檢索4451,但不一致。這是我的代碼。

try { 
BufferedReader reader = new BufferedReader((newInputStreamReader(inputStream)); 
String line = null; 
int counter = 0; 
String[] splitLine = null; 
while((line = reader.readLine()) != null){ 
    splitLine = line.split("\\|"); // Splitting the line using '|' Delimiter 
    for(String temp : splitLine) { 
     System.out.println(temp); 
    } 
    counter++; 
} 
System.out.println(counter); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

是分裂字符串和readfile在同一時間迭代可能是原因?

編輯: 情況沒有發生異常。它僅通過使用counter變量來打印長度。

我的預期輸出是我想檢索文本文件中每行的所有記錄,並將每行的字符串拆分爲pipecounter是檢索的行數。

+1

也許你正在壓制一個異常。顯示你的完整try/catch塊。並修復編譯錯誤。 – shmosel

+0

嗨@shmosel,我沒有嘗試/趕上,並沒有發生錯誤。 – msagala25

+0

必須在某處嘗試/捕捉。您發佈的代碼沒有任何問題。不要讓我們乞求[mcve]。 – shmosel

回答

-1

不應使用管道分隔符只是"|"而不是"\\|"

試試你的代碼更改爲:

splitLine = line.split("|"); // Splitting the line using '|' Delimiter 
+0

不,'split()'接受一個正則表達式。 – shmosel

+0

@shadow你的答案顯然是錯誤的。去檢查這裏:https://stackoverflow.com/questions/10796160/splitting-a-java-string-by-the-pipe-symbol-using-split – Tavo

0

我沒有找到代碼中的任何錯誤,但我寫了工作完全正常的代碼。這裏是代碼

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

class Test { 
    public static void main(String[] args) { 
     FileReader inputStream = null; 
     BufferedReader reader = null; 
     try { 
      inputStream = new FileReader("Input.txt"); 
      reader = new BufferedReader(inputStream); 
      String line = null; 
      int counter = 0; 
      String[] splitLine = null; 
      while ((line = reader.readLine()) != null) { 
       splitLine = line.split("\\|"); 
       for (String temp : splitLine) { 
        System.out.println(temp); 
       } 
       counter++; 
      } 
      System.out.println(counter); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
}