近期由于工作中有需求,需要使用到文件新增内容监控的功能
所以就弄了一个简单又能够适应通用的工具类
public class FileMonitor {
private Long point = 0l;
/**
* 轮询间隔
*/
private Long interval;
/**
* 新增内容处理
*/
private Watch watch;
private RandomAccessFile randomAccessFile;
public FileMonitor(File file) throws FileNotFoundException {
this.interval = 100l;
randomAccessFile = new RandomAccessFile(file, "r");
}
/**
* 启动监控,默认间隔0.1秒
*/
public void monitor() {
ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
scheduledExecutorService.scheduleAtFixedRate(()-> {
try {
randomAccessFile.seek(point);
String temp;
while ((temp = randomAccessFile.readLine()) != null) {
watch.doInWathch(temp);
point = randomAccessFile.getFilePointer();
}
} catch (IOException e) {
e.printStackTrace();
}
}, 0, interval, TimeUnit.MILLISECONDS);
}
public void setWatch(Watch watch) {
this.watch = watch;
}
public Long getPoint() {
return point;
}
public void setPoint(Long point) {
this.point = point;
}
interface Watch {
void doInWathch(String txt);
}
}
调用的例子代码:
public static void main(String[] args) throws IOException {
FileMonitor fileMonitor = new FileMonitor(new File("D://test.txt"));
fileMonitor.setWatch(txt -> System.out.println(txt));
fileMonitor.monitor();
}