Java 實時讀取日志文件


需求:正在開發一個監控系統,要求將日志信息實時采集出來,然后保存到ElasticSearch,后期對日志數據進行展示和分析

運用的技術:RandomAccessFile類中seek方法可以從指定位置讀取文件,可以用來實現文件實時讀取,JDK文檔有對RandomAccessFile的介紹。

關鍵點:采用一個文件讀取指針游標,每次讀取完文件后,將文件的指針位置保存到文件讀取指針游標中,下次讀取的話從文件讀取指針游標位置處開始

源代碼:

 1 package es.test.esjavaclient;
 2 
 3 import java.io.File;
 4 import java.io.RandomAccessFile;
 5 
 6 /**
 7  * 實時讀取日志文件
 8  * @author think
 9  *
10  */
11 public class FileRead {
12     //文件讀取指針游標
13     public static long pointer = 0;
14     
15     public static void main(String[] agrs){
16         while (true){
17             System.out.println("pointer:"+pointer);
18             String paht ="D:/test.txt";
19             randomRed(paht);
20             try {
21                 System.out.println("停頓開始:"+System.currentTimeMillis());
22                 //停頓10秒,方便操作日志文件,看效果。
23                 Thread.sleep(10000);
24                 System.out.println("停頓結束:"+System.currentTimeMillis());
25             } catch (InterruptedException e) {
26                 // TODO Auto-generated catch block
27                 e.printStackTrace();
28             }
29             
30         }
31     }
32     
33     /** 
34      * 讀取文件的方法 
35      * @param path 文件路徑  
36      * **/  
37     public static void randomRed(String path){  
38         try{
39             File file = new File(path);
40             if(file == null){
41                 System.out.println("文件不存在");
42                 return;
43             }
44             RandomAccessFile raf=new RandomAccessFile(file, "r"); 
45             //獲取RandomAccessFile對象文件指針的位置,初始位置是0  
46             System.out.println("RandomAccessFile文件指針的初始位置:"+raf.getFilePointer());  
47             raf.seek(pointer);//移動文件指針位置  
48             String line =null; 
49             //循環讀取 
50             while((line = raf.readLine())!=null){
51                 if(line.equals("")){
52                     continue;
53                 }
54                 //打印讀取的內容,並將字節轉為字符串輸入,做轉碼處理,要不然中文會亂碼 
55                 line = new String(line.getBytes("ISO-8859-1"),"gb2312");
56                 System.out.println("line :"+line); 
57             }  
58             //文件讀取完畢后,將文件指針游標設置為當前指針位置 。 運用這個方法可以做很多文章,比如查到自己想要的行的話,可以記下來,下次直接從這行讀取
59             pointer = raf.getFilePointer();   
60                   
61         }catch(Exception e){  
62             System.out.println("異常:"+ e.getMessage());
63             e.printStackTrace();  
64         }    
65     }  
66     
67 }
View Code

 

大家也可以參考下面這篇文章:

http://blog.csdn.net/ycb1689/article/details/53330832#;

這篇文章是將文件的大小記下來,然后下次讀取的話直接移動位置到文件末尾。 個人感覺沒有我的靈活

 

關於操作ElasticSearch部分,后續博客再更新


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM