工具类commons-io的Tailer用法,用来监控文件内容的变化情况

来源:互联网 发布:光大证券软件下载 编辑:程序博客网 时间:2024/05/17 03:32

一、前言:在Linux下有使用tail命令

      在Commons-io中也提供这种方法

二、他采用的是线程方式来监控文件内容的变化

1、Tailer类(采用线程的方式进行文件的内容变法)

2、TailerListener类

3、TailerListenerAdapter类,该类是集成了TailerListener的实现空的接口方式

三、测试使用代码

package com.yezi.leran.commons.io;import org.apache.commons.io.FileUtils;import org.apache.commons.io.IOUtils;import org.apache.commons.io.input.Tailer;import org.apache.commons.io.input.TailerListenerAdapter;import java.io.File;/** * Created by yezi on 2014/6/2. */public class TailerTest {    public static void main(String []args) throws Exception{        TailerTest tailerTest = new TailerTest();        tailerTest.test();        boolean flag = true;        File file = new File("C:/Users/yezi/Desktop/test/1.txt");        while(flag){            Thread.sleep(1000);            FileUtils.write(file,""+System.currentTimeMillis()+ IOUtils.LINE_SEPARATOR,true);        }    }    public void test() throws Exception{        File file = new File("C:/Users/yezi/Desktop/test/1.txt");        FileUtils.touch(file);        Tailer tailer = new Tailer(file,new TailerListenerAdapter(){            @Override            public void fileNotFound() {  //文件没有找到                System.out.println("文件没有找到");                super.fileNotFound();            }            @Override            public void fileRotated() {  //文件被外部的输入流改变                System.out.println("文件rotated");                super.fileRotated();            }            @Override            public void handle(String line) { //增加的文件的内容                System.out.println("文件line:"+line);                super.handle(line);            }            @Override            public void handle(Exception ex) {                ex.printStackTrace();                super.handle(ex);            }        },4000,true);        new Thread(tailer).start();    }}



0 0