需求:正在开发一个监控系统,要求将日志信息实时采集出来,然后保存到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 }
大家也可以参考下面这篇文章:
http://blog.csdn.net/ycb1689/article/details/53330832#;
这篇文章是将文件的大小记下来,然后下次读取的话直接移动位置到文件末尾。 个人感觉没有我的灵活
关于操作ElasticSearch部分,后续博客再更新