读取更新的日志
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;
}
}
多情自古空余恨
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构