读取更新的日志

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;
}

}
posted @   lem985  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示