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

后端 未结 9 1677
长发绾君心
长发绾君心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 03:28

    Try this. This give for last 5 line.

     public static void main(String[] args) throws IOException {
                List list =new ArrayList();
                FileInputStream in = new FileInputStream("C:/adminconsole.txt");
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
    
                String strLine ="", tmp;
                while ((tmp = br.readLine()) != null){ 
                    //strLine =tmp+"\n"+strLine;
                    list.add(tmp);
                    }
    
                if(list.size()>5){
                    for (int i=list.size()-1; i>=(list.size()-5); i--) {
                        System.out.println(list.get(i));
                    }
                }else{
                    for (int i=0; i<5; i++) {
                System.out.println(list.get(i));
            }
    
                }
    
            }
        }
    

提交回复
热议问题