2013-07-07 16 views
5

Robię dziennik i chcę przeczytać ostatnią linię pliku log.txt, ale mam problem z zatrzymaniem BufferedReader po ostatnim wierszu czytać.jak odczytać ostatnią linię w pliku tekstowym za pomocą java

Oto mój kod:

try { 
    String sCurrentLine; 

    br = new BufferedReader(new FileReader("C:\\testing.txt")); 

    while ((sCurrentLine = br.readLine()) != null) { 
     System.out.println(sCurrentLine); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (br != null)br.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
+0

http: // stackoverflow.com/questions/686231/java-quickly-read-the-last-line-of-a-text-file –

+2

IMO, to NIE jest duplikat pytania. –

+0

Zobacz tę odpowiedź: http://stackoverflow.com/a/11665098/548225 – anubhava

Odpowiedz

14

Oto dobry solution.

W kodzie, można po prostu stworzyć zmienną pomocniczą o nazwie lastLine i stale ponownie zainicjować go do bieżącej linii tak:

String lastLine = ""; 

    while ((sCurrentLine = br.readLine()) != null) 
    { 
     System.out.println(sCurrentLine); 
     lastLine = sCurrentLine; 
    } 
+3

Twój link jest rekurencyjny? o.O – Zong

+1

To jest zabawne. Naprawiony. –

6

Ten fragment powinien pracować dla Ciebie:

BufferedReader input = new BufferedReader(new FileReader(fileName)); 
    String last, line; 

    while ((line = in.readLine()) != null) { 
     last = line; 
    } 
    //do something with last! 
+0

Sprawdzamy stan nie null w pętli while, dlaczego potrzebujemy warunku if zagnieżdżonego w środku? – Subayan

+0

@Subayan Mistake z mojej strony, naprawiony! –

Powiązane problemy