写点什么

JAVA 实现读取最后几行日志

  • 2025-06-03
    福建
  • 本文字数:1238 字

    阅读完需:约 4 分钟

1. 背景


在项目框架设计中,针对系统产生的日志,有线上查看日志的需求.日志文件本身很大.线上查看时,开发人员只想了解当前系统产生的错误信息.


2. POM 依赖


主要使用 ReversedLinesFileReader 实现到读日志文件,需要引入 commons-io 依赖,底层使用 RandomAccessFile 实现.


 <dependency>  <groupId>commons-io</groupId>  <artifactId>commons-io</artifactId>  <version>2.6</version> </dependency>
复制代码


3. 代码实现


先倒序读取每行数据,放入集合中.然后集合倒序,返回符合阅读习惯的文本日志.


public String readLastLines(String filePath, int lines) throws IOException {  if(StringUtils.isBlank(filePath)|| lines<=0){    return "";  }  List<String> lastLine = new ArrayList<String>();  ReversedLinesFileReader reader = null;  try {    reader = new ReversedLinesFileReader(filePath, StandardCharsets.UTF_8);    String line = "";    while ((line = reader.readLine()) != null && lastLine.size() < lines) {      lastLine.add(line);    }    Collections.reverse(lastLine);  } catch (IOException e) {    System.out.println("读取文件失败,公众号:小满小慢,小游戏:地心侠士");  } finally {    if (reader != null) {      try {        reader.close();      } catch (IOException e) {        System.out.println("关闭文件失败,,公众号:小满小慢,小游戏:地心侠士");      }    }  }  return StringUtils.join(lastLine, "\r\n");}
复制代码


4. RandomAccessFile 基本使用


使用 RandomAccessFile 类,实现倒序读取内容


@Test   public void testReadLogFile() {   	File logFile = new File("./logs/spring.log");   	RandomAccessFile reader = null;   	try {   		reader = new RandomAccessFile(logFile, "r");   		System.out.println(reader.readUTF());   		reader.seek(logFile.length() - 1);   		byte c = -1;   		List<Byte> l = new ArrayList<Byte>();   		do {   			c = reader.readByte();   			if (c == '\r' || c == '\n') {   				byte[] bytes = new byte[l.size()];   				for (int i = 0; i < l.size(); i++) {   					bytes[i] = l.get(i);   				}   				String line = new String(bytes, StandardCharsets.UTF_8);   				System.out.println("地心侠士:"+ line);   				l = new ArrayList<Byte>();   			}   		} while (reader.getFilePointer() != logFile.length());   		System.out.println("地心侠士:" +logFile.length());   	} catch (IOException e) {   		e.printStackTrace();   	} finally {   		if (reader != null) {   			try {   				reader.close();   			} catch (IOException e) {
} } } }
复制代码


文章转载自:_herbert

原文链接:https://www.cnblogs.com/yfrs/p/18906865/java_read_last_line

体验地址:http://www.jnpfsoft.com/?from=001YH

用户头像

还未添加个人签名 2025-04-01 加入

还未添加个人简介

评论

发布
暂无评论
JAVA实现读取最后几行日志_Java_电子尖叫食人鱼_InfoQ写作社区