读取更新的日志
public class ReadLog {
//设置变量 记录上次读取位置
private long num = 0;
public void readAW() throws IOException {
File file = new File("/Users/shunzhang/Downloads/fio-test-zs.log");
RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
//将文件定位到偏移量所指位置,在该位置发生下一个读取或写入操作
randomAccessFile.seek(num);
//获取按行读取的数据并落库
String s = randomAccessFile.readLine();
for(;s!= null;s = randomAccessFile.readLine()){
System.out.println("打印:"+s);
}
//重新计算偏移量,做下一次读取时的初始偏移量
num= randomAccessFile.length();
}
}
public class LogView {
public static boolean firstRead = true;
public static int countdown = 0;
private long lastTimeFileSize = 0; //上次文件大小
/**
* 实时输出日志信息
*
* @param logFile 日志文件
* @throws IOException
*/
public void realtimeShowLog(File logFile) throws IOException {
//指定文件可读可写
final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
//启动一个线程每1秒钟读取新增的日志信息
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
//将文件记录指针定位到pos位置,一开始从0的位置开始读取
randomFile.seek(lastTimeFileSize);
String tmp = "";
while ((tmp = randomFile.readLine()) != null) {
String s = new String(tmp.getBytes("ISO8859-1"));
String[] split = s.trim().split("\\s+");
String s1 = Arrays.toString(split);
lastTimeFileSize = randomFile.length();
//去除空集合
if(firstRead){
System.out.println("11111: "+s1);
continue;
}
if(!s1.equals("[]")){
System.out.println("gggg: "+s1);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 1, TimeUnit.SECONDS);
}
public static void main(String[] args) throws Exception {
LogView view = new LogView();
// final File tmpLogFile = new File("/Users/shunzhang/Downloads/fio-test-zs.log");
final File tmpLogFile = new File("mock.log");
view.realtimeShowLog(tmpLogFile);
countdown = 10000;
Thread.sleep(countdown);
firstRead = false;
}
}
多情自古空余恨

浙公网安备 33010602011771号