java - 使用 Tailer 和 WatchService

标签 java watchservice apache-tailer

我通过使用以下代码同时使用 Tailer 和 WatchService:

AgentTailerListener listener = new AgentTailerListener();
Tailer tailer;

WatchService watcher = FileSystems.getDefault().newWatchService();
while (true) {
    WatchKey watchKey;
    watchKey = Paths.get("/tmp").register(watcher, ENTRY_CREATE);
    watchKey = watcher.take();

    for (WatchEvent<?> event : watchKey.pollEvents()) {
        if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
            tailSource = event.context().toString();
            System.out.println(tailSource);
            File file = new File("/tmp/" + tailSource);
            String end = "log";

            if (file.getName().endsWith(end)) {
                tailer = TailerFactory.createTailer(file, listener);
                (new Thread(tailer)).start();
            }

        }
    }

    watchKey.reset();
    transport.close();
}

但问题是:我只想用 tailer 检查一个文件(就像停止线程一样,但我无法停止特定于文件的线程),当我通过 echo 命令写入文件时,并不是所有我写的字母都会出现。

当我用 echo 连续多次写入相同的文本时,所有字母都会被写入。

我看到这个话题,How to tail -f the latest log file with a given pattern ,但我不知道是否可以用它来解决我的问题(我不知道 tail 和 tailer 之间的区别)。

最佳答案

最后,我认为这样效果更好:

AgentTailerListener listener = new AgentTailerListener();
Tailer tailer;
String tailSource;
Thread thread;

WatchService watcher = FileSystems.getDefault().newWatchService();

WatchKey watchKey;
watchKey = Paths.get("/tmp").register(watcher, ENTRY_CREATE);

List<Thread> threadList = new ArrayList<Thread>();
while (true) {
    watchKey = watcher.take();
    for (WatchEvent<?> event : watchKey.pollEvents()) {
    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {

        tailSource = event.context().toString();
        System.out.println(tailSource);
        File file = new File("/tmp/" + tailSource);
        String end = "log";
        if (file.getName().endsWith(end)) {
            tailer= TailerFactory.createTailer(file, listener);
            if(threadList.isEmpty()){}
            else{
                Thread.sleep(1000);
                threadList.get(0).stop();
                threadList.clear();}
            System.out.println(threadList.size());
            threadList.add(thread = new Thread(tailer));
            threadList.get(0).start();
            }
    }
}
watchKey.reset();

} 

但是它创建了很多线程,我想我必须使用修复线程池。

关于java - 使用 Tailer 和 WatchService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31568820/

相关文章:

java - 从特定 USB 端口捕获键盘输入

javascript - 为什么 tail 长文件会导致 chrome 崩溃?

java - 多路复用器不处理第二个输入处理器

java - 通过 Bungee 将玩家发送到另一个服务器

java - 运行 GWT 时出现空白(白色)页错误

java - 如何使用 WatchService 监视子目录的变化? ( java )

java - WatchService:注册时传递参数

Windows 上的 Java WatchService 在复制内容之前通知文件夹创建

java - 拖尾文件时java中的巨大虚拟内存

java - 如何避免 TailerListener 中的旧日志消息