Java即時讀取記錄檔__Java

來源:互聯網
上載者:User

 

在一台伺服器上寫記錄檔,每當記錄檔寫到一定大小時,比如是1G,會將這個記錄檔改名成另一個名字,並建立一個與原檔案名稱相同的記錄檔,再往這個建立的記錄檔裡寫資料;要求寫一個程式能即時地讀取記錄檔中的內容,並且不能影響寫操作與重新命名操作。

RandomAccessFile類中seek方法可以從指定位置讀取檔案,可以用來實現檔案即時讀取。JDK文檔對RandomAccessFile的介紹

在每一次讀取後,close一下就不會影響重新命名操作了。

寫記錄檔,每秒寫200條記錄,並且記錄寫的時間

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 LogWrite implements Runnable {      private File logFile = null;    private SimpleDateFormat dateFormat =           new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      public LogWrite(File logFile) {    this.logFile = logFile;}      /**      * 將資訊記錄到記錄檔      * @param logFile 記錄檔      * @param mesInfo 資訊      * @throws IOException       */      public void run(){          if(logFile == null) {              throw new IllegalStateException("logFile can not be null!");          }         try {            if(!logFile.exists()) {          logFile.createNewFile();          }         //啟動一個線程每1秒鐘向記錄檔寫一次資料              ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);              exec.scheduleWithFixedDelay(new Runnable(){                 public void run() {                     try {                     Writer txtWriter = new FileWriter(logFile,true);                  txtWriter.write(dateFormat.format(new Date()) +"\t 99bill test ! \n");                    txtWriter.flush();                       } catch (IOException e) {                         throw new RuntimeException(e);                     }                 }             }, 0, 1, TimeUnit.SECONDS);         } catch (IOException e) { e.printStackTrace();}      }                public static void main(String[] args) throws Exception{                    final File tmpLogFile = new File("mock.log");          final LogWrite logSvr = new LogWrite(tmpLogFile);             //啟動一個線程每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.NANOSECONDS);*/      }  }  


即時讀取記錄檔,每隔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 {                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();            }        }    }}

開啟寫線程、讀線程,將即時資訊列印在控制台。

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檔案重新命名,發現依舊可以即時讀。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.