Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

java - Apache Commons IO Tailer example

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);
    }
}

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. I tried to find a concrete example of usage of Tailer class, but no luck. What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...