How to read last 5 lines of a .txt file into java

后端 未结 9 1641
长发绾君心
长发绾君心 2020-12-15 03:03

I have a text file that consists of several entries such as:

hello
there
my
name
is
JoeBloggs

How would I read the last five entries in des

9条回答
  •  春和景丽
    2020-12-15 03:32

    You can add the lines to a List, e.g. a LinkedList. When the list has more than five lines, remove the first/last.

    List lines = new LinkedList();
    for(String tmp; (tmp = br.readLine()) != null;) 
        if (lines.add(tmp) && lines.size() > 5) 
            lines.remove(0);
    

提交回复
热议问题