Java How to read last few lines of a File

摘要: In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File.

In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File.

pom.xml
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.6</version>
	</dependency>

1. Test Data

A server log file sample

d:\\server.log

2. Read Last Line

2.1 Read the last 3 lines of a file.

TestReadLastLine.java
package com.mkyong.io;
import org.apache.commons.io.input.ReversedLinesFileReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class TestReadLastLine {
    public static void main(String[] args) {
        List<String> lines = readLastLine(new File("D:\\server.log"), 3);
        lines.forEach(x -> System.out.println(x));
    public static List<String> readLastLine(File file, int numLastLineToRead) {
        List<String> result = new ArrayList<>();
        try (ReversedLinesFileReader reader = new ReversedLinesFileReader(file, StandardCharsets.UTF_8)) {
            String line = "";
            while ((line = reader.readLine()) != null && result.size() < numLastLineToRead) {
                result.add(line);
        } catch (IOException e) {
            e.printStackTrace();
        return result;

Output



上一篇: Java How to lock a file before writing
下一篇: Spring Boot JDBC Stored Procedure Examples
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号