博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java实时读取日志文件
阅读量:6958 次
发布时间:2019-06-27

本文共 4432 字,大约阅读时间需要 14 分钟。

古怪的需求

在实习的公司碰到一个古怪的需求:在一台服务器上写日志文件,每当日志文件写到一定大小时,比如是1G,会将这个日志文件改名成另一个名字,并新建一个与原文件名相同的日志文件,再往这个新建的日志文件里写数据;要求写一个程序能实时地读取日志文件中的内容,并且不能影响写操作与重命名操作。

RandomAccessFile类中seek方法可以从指定位置读取文件,可以用来实现文件实时读取。JDK文档对RandomAccessFile的介绍

Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended.

在每一次读取后,close一下就不会影响重命名操作了。

编码实现

代码参考,。

写日志文件,每秒写200条记录,并且记录写的时间

import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.text.SimpleDateFormat;import java.util.Date;public class LogReader implements Runnable {    private File logFile = null;    private long lastTimeFileSize = 0; // 上次文件大小    private static SimpleDateFormat dateFormat = new SimpleDateFormat(            "yyyy-MM-dd HH:mm:ss");    public LogReader(File logFile) {        this.logFile = logFile;        lastTimeFileSize = logFile.length();    }    /**     * 实时输出日志信息     */    public void run() {        while (true) {            try {                long len = logFile.length();                if (len < lastTimeFileSize) {                    System.out.println("Log file was reset. Restarting logging from start of file.");                    lastTimeFileSize = len;                } else if(len > lastTimeFileSize) {                    RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");                    randomFile.seek(lastTimeFileSize);                    String tmp = null;                    while ((tmp = randomFile.readLine()) != null) {                        System.out.println(dateFormat.format(new Date()) + "\t"                                + tmp);                    }                    lastTimeFileSize = randomFile.length();                    randomFile.close();                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }                        try {                Thread.sleep(50);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}

实时读取日志文件,每隔1秒读一次

import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.text.SimpleDateFormat;import java.util.Date;public class LogReader implements Runnable {    private File logFile = null;    private long lastTimeFileSize = 0; // 上次文件大小    private static SimpleDateFormat dateFormat = new SimpleDateFormat(            "yyyy-MM-dd HH:mm:ss");    public LogReader(File logFile) {        this.logFile = logFile;        lastTimeFileSize = logFile.length();    }    /**     * 实时输出日志信息     */    public void run() {        while (true) {            try {                RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");                randomFile.seek(lastTimeFileSize);                String tmp = null;                while ((tmp = randomFile.readLine()) != null) {                    System.out.println(dateFormat.format(new Date()) + "\t"                            + tmp);                }                lastTimeFileSize = randomFile.length();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            try {                Thread.sleep(500);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}

开启写线程、读线程,将实时信息打印在控制台。

import java.io.File;public class RunRun {    public static void main(String[] args) {        File logFile = new File("mock.log");        Thread wthread = new Thread(new LogWrite(logFile));        wthread.start();        Thread rthread = new Thread(new LogReader(logFile));        rthread.start();    }}

在读写的过程中,我们可以手动将mock.log文件重命名,发现依旧可以实时读。

转载于:https://www.cnblogs.com/en-heng/p/3926708.html

你可能感兴趣的文章
.NET开发技巧——从Winform穿越到WPF
查看>>
2135亿背后的双11项目协作怎么玩?
查看>>
DRDS SQL 审计与分析——全面洞察 SQL 之利器
查看>>
微信小程序:模板消息推送实现
查看>>
自己总结的php开发中用到的工具
查看>>
PHP导出超大的CSV格式的Excel表方案
查看>>
jenkins 使用磁盘检查插件 disk check plugin
查看>>
使用 Ruby 拓展 Vim
查看>>
centos7下安装LNMP(nginx+PHP7.1.9+mysql5.7)
查看>>
深入java单例模式
查看>>
create-react-app
查看>>
20170812-XSS跨站脚本攻击
查看>>
Let’s Build |> 使用Elixir,Phoenix和React打造克隆版的Slack(part 1)
查看>>
如何让 StackNaivgator 实现越级回跳
查看>>
工具简述
查看>>
Hbase 集群搭建
查看>>
关于直播视频格式和浏览器兼容性历史的来龙去脉
查看>>
是的,InfoQ正在招聘技术编辑!跟对的人,一起做喜欢的事!
查看>>
vue2+vue-cli,dis文件加载出错解决方案
查看>>
立下“去O”Flag的AWS,悄悄修炼了哪些内功?
查看>>