[英]Apache Commons IO Tailer example
I am working on a monitoring program that reads the /var/log/auth.log file.我正在开发一个读取 /var/log/auth.log 文件的监控程序。 I am using Apache Commons IO
Tailer
class to read the file in real time.我正在使用 Apache Commons IO
Tailer
类实时读取文件。 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);
}
}
And from the terminal : sudo echo "Hello" >> log.txt
The problem is when I try to write manually something in the file, it does not print it in the console.从终端:
sudo echo "Hello" >> log.txt
问题是当我尝试在文件中手动写入某些内容时,它不会在控制台中打印出来。 I tried to find a concrete example of usage of Tailer class, but no luck.我试图找到一个使用 Tailer 类的具体例子,但没有运气。 What am I doing wrong here?
我在这里做错了什么?
Based on my testing, Tailer
will only print a line when you've added a newline to the file.根据我的测试,当您向文件添加换行符时,
Tailer
只会打印一行。 So try sudo echo "Hello\\n" >> log.txt
所以试试
sudo echo "Hello\\n" >> log.txt
Also note that if you call create
, you start a thread but have no handle on it.另请注意,如果您调用
create
,则会启动一个线程但没有处理它。 Hence why you had to have a while/true loop.因此,为什么你必须有一个 while/true 循环。
You could try this instead:你可以试试这个:
public static void main(String[] args) {
TailerListener listener = new MyListener();
Tailer tailer = new Tailer(new File("log.txt"), listener, 500);
tailer.run();
}
Your code should work.您的代码应该可以工作。 For me, this does works as expected.
对我来说,这确实按预期工作。
package de.lhorn.stackoverflowplayground;
import java.io.File;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListenerAdapter;
public class App {
private static final int SLEEP = 500;
public static void main(String[] args) throws Exception {
App app = new App();
app.run();
}
private void run() throws InterruptedException {
MyListener listener = new MyListener();
Tailer tailer = Tailer.create(new File("/tmp/log.txt"), listener, SLEEP);
while (true) {
Thread.sleep(SLEEP);
}
}
public class MyListener extends TailerListenerAdapter {
@Override
public void handle(String line) {
System.out.println(line);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.