在一台服务器上写日志文件,每当日志文件写到一定大小时,比如是1G,会将这个日志文件改名成另一个名字,并新建一个与原文件名相同的日志文件,再往这个新建的日志文件里写数据;要求写一个程序能实时地读取日志文件中的内容,并且不能影响写操作与重命名操作。
RandomAccessFile类中seek方法可以从指定位置读取文件,可以用来实现文件实时读取。JDK文档对RandomAccessFile的介绍
在每一次读取后,close一下就不会影响重命名操作了。
写日志文件,每秒写200条记录,并且记录写的时间
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class LogWrite implements Runnable {
private File logFile = null;
private SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public LogWrite(File logFile) {
= logFile;
}
/**
* 将信息记录到日志文件
* @param logFile 日志文件
* @param mesInfo 信息
* @throws IOException
*/
public void run(){
if(logFile == null) {
throw new IllegalStateException("logFile can not be null!");
}
try {
if(!()) {
();
}
//启动一个线程每1秒钟向日志文件写一次数据
ScheduledExecutorService exec = (1);
(new Runnable(){
public void run() {
try {
Writer txtWriter = new FileWriter(logFile,true);
((new Date()) +"\t 99bill test ! \n");
();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 1, );
} catch (IOException e) {
();
}
}
public static void main(String[] args) throws Exception{
final File tmpLogFile = new File("");
final LogWrite logSvr = new LogWrite(tmpLogFile);
//启动一个线程每5秒钟向日志文件写一次数据
/* ScheduledExecutorService exec =
(1);
(new Runnable(){
public void run() {
try {
(tmpLogFile, " 99bill test !");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 5, );*/
}
}
import ;
import ;
import ;
import ;
import ;
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) {
= logFile;
lastTimeFileSize = ();
}
/**
* 实时输出日志信息
*/
public void run() {
while (true) {
try {
long len = ();
if (len < lastTimeFileSize) {
("Log file was reset. Restarting logging from start of file.");
lastTimeFileSize = len;
} else if(len > lastTimeFileSize) {
RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");
(lastTimeFileSize);
String tmp = null;
while ((tmp = ()) != null) {
((new Date()) + "\t"
+ tmp);
}
lastTimeFileSize = ();
();
}
} catch (IOException e) {
// TODO Auto-generated catch block
();
}
try {
(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
();
}
}
}
}
开启写线程、读线程,将实时信息打印在控制台。
import ;
public class RunRun {
public static void main(String[] args) {
File logFile = new File("");
Thread wthread = new Thread(new LogWrite(logFile));
();
Thread rthread = new Thread(new LogReader(logFile));
();
}
}
在读写的过程中,我们可以手动将文件重命名,发现依旧可以实时读。