Java實時監控日誌文件並輸出的方法詳解
想在前臺顯示數據同步過程當中產生的日誌文件,在網上找到解決方案,作了代碼測試好用。這裏作個記錄html
java.io.RandomAccessFile
能夠解決同時向文件讀和寫.爲了模擬這個問題,編寫LogSvr和 LogView類,LogSvr不斷向mock.log日誌文件寫數據,而 LogView則實時輸出日誌變化部分的數據.java
代碼1:日誌產生類
package com.fbkj.genelog; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; 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 LogSvr { private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 將信息記錄到日誌文件 * @param logFile 日誌文件 * @param mesInfo 信息 * @throws IOException */ public void logMsg(File logFile,String mesInfo) throws IOException{ if(logFile == null) { throw new IllegalStateException("logFile can not be null!"); } Writer txtWriter = new FileWriter(logFile,true); txtWriter.write(dateFormat.format(new Date()) +"\t"+mesInfo+"\n"); txtWriter.flush(); } public static void main(String[] args) throws Exception{ final LogSvr logSvr = new LogSvr(); String userdir = System.getProperty("user.dir"); final File tmpLogFile = new File(userdir+"/mock.log"); if(!tmpLogFile.exists()) { tmpLogFile.createNewFile(); } //啓動一個線程每5秒鐘向日志文件寫一次數據 ScheduledExecutorService exec = Executors.newScheduledThreadPool(1); exec.scheduleWithFixedDelay(new Runnable(){ public void run() { try { logSvr.logMsg(tmpLogFile, " 99bill test !"); } catch (IOException e) { throw new RuntimeException(e); } } }, 0, 5, TimeUnit.SECONDS); } }
代碼2:顯示日誌的類
package com.fbkj.genelog; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class LogView { private long lastTimeFileSize = 0; //上次文件大小 /** * 實時輸出日誌信息 * @param logFile 日誌文件 * @throws IOException */ public void realtimeShowLog(File logFile) throws IOException{ //指定文件可讀可寫 final RandomAccessFile randomFile = new RandomAccessFile(logFile,"rw"); //啓動一個線程每10秒鐘讀取新增的日誌信息 ScheduledExecutorService exec = Executors.newScheduledThreadPool(1); exec.scheduleWithFixedDelay(new Runnable(){ public void run() { try { //得到變化部分的 randomFile.seek(lastTimeFileSize); String tmp = ""; while( (tmp = randomFile.readLine())!= null) { System.out.println(new String(tmp.getBytes("ISO8859-1"))); } lastTimeFileSize = randomFile.length(); } catch (IOException e) { throw new RuntimeException(e); } } }, 0, 1, TimeUnit.SECONDS); } public static void main(String[] args) throws Exception { String userdir = System.getProperty("user.dir"); LogView view = new LogView(); final File tmpLogFile = new File(userdir+"/mock.log"); view.realtimeShowLog(tmpLogFile); } }
先執行LogSvr類,LogSvr類會啓動一個線程,每5秒鐘向mock.log日誌文件寫一次數據,dom
而後再執行LogView類,LogView每隔1秒鐘讀一次,若是數據有變化則輸出變化的部分.測試