本文介绍了Apache Commons IO Tailer示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个读取/var/log/auth.log文件的监控程序。我正在使用Apache Commons IO 类可实时读取文件。首先,我想在一个简单的文件上测试实时阅读部分,并在控制台行中手动输入一些代码。这是我的代码:

I am working on a monitoring program that reads the /var/log/auth.log file. I am using Apache Commons IO Tailer class to read the file in real time. To get started, I wanted to test the real-time reading part on a simple file, and manually enter some code in the console line. Here is my code:

public class Main {
    public static void main(String[] args) {
        TailerListener listener = new MyListener();
        Tailer tailer = Tailer.create(new File("log.txt"), listener, 500);
        while(true) {

        }
    }
}

public class MyListener extends TailerListenerAdapter {
    @Override
    public void handle(String line) {
        System.out.println(line);
    }
}

从终端: sudo echo你好>> log.txt
问题是当我尝试在文件中手动编写某些东西时,它不会在控制台中打印它。我试图找到一个使用Tailer类的具体例子,但没有运气。我在这里做错了什么?

And from the terminal : sudo echo "Hello" >> log.txtThe problem is when I try to write manually something in the file, it does not print it in the console. I tried to find a concrete example of usage of Tailer class, but no luck. What am I doing wrong here?

推荐答案

根据我的测试, Tailer 只有在向文件添加换行符时才会打印一行。所以尝试 sudo echoHello\\\
>> log.txt

Based on my testing, Tailer will only print a line when you've added a newline to the file. So try sudo echo "Hello\n" >> log.txt

另请注意,如果您调用 create ,则启动一个线程但没有处理它。因此,为什么你必须有一个while / true循环。

Also note that if you call create, you start a thread but have no handle on it. Hence why you had to have a while/true loop.

你可以试试这个:

public static void main(String[] args) {
    TailerListener listener = new MyListener();
    Tailer tailer = new Tailer(new File("log.txt"), listener, 500);
    tailer.run();
}

这篇关于Apache Commons IO Tailer示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:15