古怪的需求#

在实习的公司碰到一个古怪的需求:在一台服务器上写日志文件,每当日志文件写到一定大小时,比如是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一下就不会影响重命名操作了。

编码实现#

代码参考Java实时监控日志文件并输出LogTailer.java

写日志文件,每秒写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文件重命名,发现依旧可以实时读。

Java实时读取日志文件的更多相关文章

  1. RandomAccessFile实时读取大文件(转)

    最近有一个银行数据漂白系统,要求操作人员在页面调用远端Linux服务器的shell,并将shell输出的信息保存到一个日志文件,前台页面要实时显示日志文件的内容.这个问题难点在于如何判断哪些数据是新增 ...

  2. Java快速读取大文件

    Java快速读取大文件 最近公司服务器监控系统需要做一个东西来分析Java应用程序的日志. 第一步探索: 首先我想到的是使用RandomAccessFile,因为他可以很方便的去获取和设置文件指针,下 ...

  3. Linux 实时查看日志文件动态内容

    tailf 27.log | grep 'Classcomment/praise'               'Classcomment/praise' 接口名:查看请求固定接口的时间,实时 tai ...

  4. 大数据学习day20-----spark03-----RDD编程实战案例(1 计算订单分类成交金额,2 将订单信息关联分类信息,并将这些数据存入Hbase中,3 使用Spark读取日志文件,根据Ip地址,查询地址对应的位置信息

    1 RDD编程实战案例一 数据样例 字段说明: 其中cid中1代表手机,2代表家具,3代表服装 1.1 计算订单分类成交金额 需求:在给定的订单数据,根据订单的分类ID进行聚合,然后管理订单分类名称, ...

  5. 五种方式让你在java中读取properties文件内容不再是难题

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  6. java中读取特殊文件的类型

    java中读取特殊文件的类型: 第一种方法(字符拼接读取): public static String getType(String s){ String s1=s.substring(s.index ...

  7. tail -f 实时查看日志文件 linux查看日志后100行

    tail -f 实时查看日志文件 tail -f 日志文件logtail - 100f 实时查看日志文件 后一百行tail -f -n 100 catalina.out linux查看日志后100行搜 ...

  8. Storm 实时读取本地文件操作(模拟分析网络日志)

    WebLogProduct 产生日志类 package top.wintp.weblog; import java.io.FileNotFoundException; import java.io.F ...

  9. flume读取日志文件并存储到HDFS

    配置hadoop环境 配置flume环境 配置flume文件 D:\Soft\apache-flume-1.8.0-bin\conf 将 flume-conf.properties.template ...

随机推荐

  1. <2048>游戏问卷调查心得与体会

    这是我的首次做问卷调查,刚开始感到不知所措,不知道该怎么去完成它,但是其中也充满了所谓的新鲜感,以前总是填别人做的问卷调查,但是现在是我们小组自己讨论得到的一张属于自己的问卷,可以说感受很深,一张小小 ...

  2. Mac OS X 10.9.3 UI 设置界面无法设置时区解决

    10.9.3 在选项设置里无法设置时区,表现为选择时区的点的位置后无法保存,导致系统时间错乱,解决方法是用终端设置: sudo systemsetup -gettimezone sudo system ...

  3. file /usr/share/mysql/... conflicts with file from package mysql-libs-5.1.73-3.el6_5.x86_ 64 MySQL安装

    在CentOS 6.5安装MySQL 5.6.17,安装到最后一个rpm文件MySQL-server时 安装命令是:rpm -ivh MySQL-server-5.6.17-1.el6.x86_64. ...

  4. C++ REST SDK的基本用法

    微软开发了一个开源跨平台的http库--C++ REST SDK(http://casablanca.codeplex.com/),又名卡萨布兰卡Casablanca,有个电影也叫这个名字,也许这个库 ...

  5. 图解:Arcgis Server 安装

    必须保证IIS配置正常,否则arcserver安装不会成功. 选择安装路径,还是尽量不要在有括号的文件夹下. 设置服务名,最好使用默认的. 点击完成后会要求进行服务配置. 在windows serve ...

  6. node(规则引擎)

    本文主要记录node的下的一个开源规则引擎nools,给出简单的实例,github地址为: https://github.com/C2FO/nools 定义规则引擎(test.nools) defin ...

  7. 《你必须知道的.NET》读书笔记三:体验OO之美

    此篇已收录至<你必须知道的.Net>读书笔记目录贴,点击访问该目录可以获取更多内容. 一.依赖也是哲学 (1)本质诠释:“不要调用我们,我们会调用你” (2)依赖和耦合: ①无依赖,无耦合 ...

  8. 细说.NET中的多线程 (五 使用信号量进行同步)

    上一节主要介绍了使用锁进行同步,本节主要介绍使用信号量进行同步 使用EventWaitHandle信号量进行同步 EventWaitHandle主要用于实现信号灯机制.信号灯主要用于通知等待的线程.主 ...

  9. Lucene系列-facet

    1.facet的直观认识 facet:面.切面.方面.个人理解就是维度,在满足query的前提下,观察结果在各维度上的分布(一个维度下各子类的数目). 如jd上搜“手机”,得到4009个商品.其中品牌 ...

  10. document对象

    document 对象是操作网页内容的 找元素 1.根据id找 document.getElementById(); 2.根据class找 document.getElementsByClassNam ...