本篇内容介绍了“怎么用Java实时读取日志文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
编码实现
写日志文件,每秒写200条记录,并且记录写的时间
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.text.SimpleDateFormat; import java.util.Date; 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) { this.logFile = logFile; lastTimeFileSize = logFile.length(); } /** * 实时输出日志信息 */ public void run() { while (true) { try { long len = logFile.length(); if (len < lastTimeFileSize) { System.out.println("Log file was reset. Restarting logging from start of file."); lastTimeFileSize = len; } else if(len > lastTimeFileSize) { RandomAccessFile randomFile = new RandomAccessFile(logFile, "r"); randomFile.seek(lastTimeFileSize); String tmp = null; while ((tmp = randomFile.readLine()) != null) { System.out.println(dateFormat.format(new Date()) + "\t" + tmp); } lastTimeFileSize = randomFile.length(); randomFile.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
实时读取日志文件,每隔1秒读一次
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.text.SimpleDateFormat; import java.util.Date; 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) { this.logFile = logFile; lastTimeFileSize = logFile.length(); } /** * 实时输出日志信息 */ public void run() { while (true) { try { RandomAccessFile randomFile = new RandomAccessFile(logFile, "r"); randomFile.seek(lastTimeFileSize); String tmp = null; while ((tmp = randomFile.readLine()) != null) { System.out.println(dateFormat.format(new Date()) + "\t" + tmp); } lastTimeFileSize = randomFile.length(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
开启写线程、读线程,将实时信息打印在控制台。
import java.io.File; public class RunRun { public static void main(String[] args) { File logFile = new File("mock.log"); Thread wthread = new Thread(new LogWrite(logFile)); wthread.start(); Thread rthread = new Thread(new LogReader(logFile)); rthread.start(); } }
在读写的过程中,我们可以手动将mock.log文件重命名,发现依旧可以实时读。
“怎么用Java实时读取日志文件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。