java根据文件游标实时读取日志文件

本文介绍了一种使用Java实现的实时读取日志文件的方法。通过维护文件读取指针,程序能够持续监听并输出日志文件中新增的内容,适用于监控日志更新的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.File;
import java.io.RandomAccessFile;
 
/**
 * 实时读取日志文件
 * @author sun
 * @date 2018年4月20日 下午9:51:36
 */
public class FileRead {
    // 文件读取指针游标,所谓游标就是从文件的第几个字节开始读取
    public static long pointer = 0;
 
    public static void main(String[] agrs) {
        System.err.println("开始从“"+pointer+"”游标开始读取");
        while (true) {
            String paht = "/Users/sun/Documents/workspace/workspace/sys_sunjs/logs/report.log";
            randomRed(paht);
            try {
                Thread.sleep(3000);//停顿3秒,根据自己的情况定
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 读取文件的方法
     * @author sun
     * @date 2018年4月20日 下午9:51:46
     * @param path
     */
    public static void randomRed(String path) {
        try {
            File file = new File(path);
            if (file == null || file.length()<1) {
                System.out.println("文件不存在");
                return;
            }
            @SuppressWarnings("resource")
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            // 获取RandomAccessFile对象文件指针的位置,初始位置是0
            raf.seek(pointer);// 移动文件指针位置
            String line = null;
            boolean flag = false;
            // 循环读取
            while ((line = raf.readLine()) != null) {
                flag = true;
                if (line.equals("")) {
                    continue;
                }
                // 打印读取的内容,并将字节转为字符串输入,做转码处理,要不然中文会乱码
                line = new String(line.getBytes("ISO-8859-1"),"utf-8");
                System.out.println(line);
            }
            // 文件读取完毕后,将文件指针游标设置为当前指针位置 。
            // 运用这个方法可以做很多文章,比如查到自己想要的行的话,可以记下来,下次直接从这行读取
            pointer = raf.getFilePointer();
            if(flag){
                System.err.println("当前文件游标:"+pointer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/78864639fa10400191d9d01245362dcd.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值