2016-02-18 48 views
0

每次點擊我有一個包含多個條目,例如文本文件:閱讀每個5線按鈕

one 
two 
three 
four 
five 
six 

文本文件包含100行,我想在一次讀取每個5線。我有這樣的代碼,但它給空值:

BufferedReader br = null; 
String sCurrentLine; 
int lines = 0; 
try { 
    br = new BufferedReader(new   
    FileReader("https://stackoverflow.com/users/MoathIbrahem/Desktop/Questions.txt")); 
    while(br.readLine()!= null)lines++; 
     for(int i = 0;i < lines;i++) 
      System.out.println(br.readLine()); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

回答

0

這是發生,因爲當你讀一行讀者指針的進步。當您嘗試讀取for循環時,此指針已到達文檔的末尾。

我建議你不要數線以前。喜歡的用戶gotomanners在他answer說:

String line; 
while ((line = fileReader.readLine()) != null) { 
    System.out.println(line); 
} 
+0

非常感謝。 但如果我想讀一次一次的每5行,循環將如何? –

+0

使用計數器變量,如:int currentLines = 0 –

+0

是的,這是工作,謝謝。 –

1

在這一行

while(br.readLine()!= null)lines++; 

你要閱讀所有的文本文件。

沒有更多的閱讀,除非你重新打開文件,或者使用mark/reset

+0

非常感謝^ _^ –