package com.email.service.impl;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LogView {
private long lastTimeFileSize = 0;
private long count = 0;
public void realtimeShowLog(File logFile) throws IOException {
final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
ScheduledExecutorService exec = Executors.newScheduledThreadPool(2);
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
if (count!=0){
randomFile.seek(lastTimeFileSize);
String tmp = "";
while ((tmp = randomFile.readLine()) != null) {
System.out.println(new String(tmp.getBytes("ISO8859-1")));
}
}else {
count=1;
}
lastTimeFileSize = randomFile.length();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 5, TimeUnit.SECONDS);
exec.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
randomFile.seek(lastTimeFileSize);
String msg=format.format(new Date())+"-----------------系统报错---------------";
randomFile.write(msg.getBytes());
randomFile.write("\r\n".getBytes());
}catch (IOException e) {
throw new RuntimeException(e);
}
}
},1,10,TimeUnit.SECONDS);
}
public static void main(String[] args) throws Exception {
LogView view = new LogView();
final File tmpLogFile = new File("D:\\file111.txt");
view.realtimeShowLog(tmpLogFile);
}
}