0

I use the apache tailer for read end of line, if there is adding new line inside file log the program will print just end of line, it's like "tail -f" from linux, i have the output tail to send with String.

Can i get the output tail and save to string for my code below ?

public class LogTailTest {

/**
* TailerListener implementation.
*/
static public class ShowLinesListener extends TailerListenerAdapter {
    @Override
    public void handle(String line) {
        System.out.println(line);
    }
}

public static void main(String args[]) {

    TailerListener listener  = new ShowLinesListener();
    File file = new File("/home/ubuntu/Desktop/test.log");

    Tailer tailer = new Tailer(file, listener, 10000, true, true);
    tailer.run();

    try {
        Thread.sleep(1000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    tailer.stop();

}

}

When i run above program it's direct to output console

dhaavhincy
  • 52
  • 13

1 Answers1

0

You define what to do every time a new line is tailed by your program. This behaviour is defined in the method handle of class ShowLinesListener:

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

All you have to do is change this line

System.out.println(line);

to do what you want with it. As you are already using commons-io library (that's where the TailerListener and TailerListenerAdapter classes are defined), you can use FileUtils.writeStringtoFile method to write the contents of the line just tailed to another file.

Your class would look like this:

public class LogTailTest {

/**
* TailerListener implementation.
*/
static public class ShowLinesListener extends TailerListenerAdapter {
    @Override
    public void handle(String line) {
        FileUtils.writeStringtoFile(new File("/path/to/file"),
                                    line,
                                    Charset.defaultCharset())
    }
}
gmauch
  • 1,316
  • 4
  • 25
  • 39