采用Apache Commons IO 类实现
1、Apache Commons IO 提供了高级的文件监听器(FileAlterationMonitor)和监听器适配器(FileAlterationListenerAdaptor),简化了监听文件变化的过程。
2、可以更轻松地实现监听器,并提供了多种事件(文件修改、创建、删除等)的监听。
package com.sinorail.ferry.utils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* @Author wangchang
* @Description
* @Date 2024/3/25 11:07
*/
public class WatchVsftpdLogUtil {
private static final Logger log = LoggerFactory.getLogger(WatchVsftpdLogUtil.class);
public static void main(String[] args) throws Exception {
// 指定要监听的文件路径
String filePath = "C:\\Users\\86156\\Desktop\\upload\\test.txt";
// 创建一个文件变化监视器
FileAlterationObserver observer = new FileAlterationObserver(new File(filePath).getParent());
FileListener listener = new FileListener(filePath);
observer.addListener(listener);
// 设置文件变化监视器的轮询间隔(以毫秒为单位)
long pollingInterval = 1000; // 1秒
FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
monitor.addObserver(observer);
// 启动监视器以开始监听文件的改变
monitor.start();
// 运行一段时间后停止监视器
// Thread.sleep(60000); // 监听 60 秒
// monitor.stop();
}
}
package com.sinorail.ferry.utils;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* @Author wangchang
* @Description
* @Date 2024/3/25 15:10
*/
public class FileListener extends FileAlterationListenerAdaptor {
private static final Logger log = LoggerFactory.getLogger(FileListener.class);
private String filePath;
private long lastPosition = 0;
private long lastFileSize = 0;
public FileListener(String filePath) {
this.filePath = filePath;
}
@Override
public void onFileCreate(File file) {
//TODO 创建
}
@Override
public void onFileChange(File file) {
if (file.getPath().equals(filePath)) {
log.info("File modified: " + file.getPath());
// 日志会周期性删除,这里判断如果当前文件小于上一次记录的,就重新开始记录位置
if (file.length() < lastFileSize) {
lastPosition = 0;
}
// 打开文件并定位到上次记录的位置
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
randomAccessFile.seek(lastPosition);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(randomAccessFile.getFD()), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
// 在这里可以对读取到的内容进行处理
if (StrUtil.isNotEmpty(line)) {
System.out.println("修改的内容::" + line);
}
}
// 更新记录的位置为文件的当前长度
lastPosition = randomAccessFile.getFilePointer();
// 记录当前文件的大小
lastFileSize = file.length();
}
} catch (IOException ex) {
// 可以记录错误信息或者继续监听其他事件
ex.printStackTrace();
}
}
}
@Override
public void onFileDelete(File file) {
// TODO 删除
}
}