简体   繁体   English

获取输出控制台尾部并保存到字符串Java?

[英]Get output console tail and save to string Java?

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. 我使用apache tailer读取行尾,如果在文件日志中添加了新行,程序将只打印行尾,就像linux的“ tail -f”一样,我有输出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 当我在上述程序上运行时,直接进入输出控制台

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 : 此行为在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. 由于您已经在使用commons-io库(定义了TailerListenerTailerListenerAdapter类的位置),因此可以使用FileUtils.writeStringtoFile方法将行尾的内容写入另一个文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM