Java “tail -f” wrapper

核能气质少年 提交于 2019-12-05 02:23:56

问题


I need to wrap the Unix command "tail -f" in a BufferedInputStream. I don't want to simulate or mimic tail as stated by this question. Rather, I want to use tail, waiting for it to give me a new line.


回答1:


Your best bet is to use the Process class and read with a Scanner:

Runtime r = Runtime.getRuntime()
Process p = r.exec("tail -f")
Scanner s = new Scanner(p.getInputStream())
while (s.hasNextLine()) {
    String line = s.nextLine()
    // Do whatever you want with the output.
}

hasNextLine() should block as it's waiting for more input from the input stream, so you will not be busy-waiting as data comes in.




回答2:


Look at Runtime.exec(String command). Returns a Process object that has Input and Output Streams.




回答3:


check also ProcessBuilder:

Process tail = new ProcessBuilder("tail", "-f", file).start();
BufferedInputStream bis = new BufferedInputStream(tail.getInputStream())

where file is String like "/var/log/messages".




回答4:


I am guessing that system() and popen() type approaches will not work as they will block your program until the tail command terminates.

I think you could redirect the output to a file and use 'diff' against the last version to see which lines are new?




回答5:


If you have the unix command

tail -f <file> | <some java program>

Then the tail would appear as an InputStream that may block for a period of time. If you don't want to block yourself, you would use the nio packages. I believe that most other ways to access the tail command (such as Process) results in a similar InputStream.




回答6:


Two more full blown projects:

http://www.eclipse.org/tptp/home/documents/tutorials/gla/gettingstarted_gla.html

http://commons.apache.org/io/api-release/org/apache/commons/io/input/Tailer.html



来源:https://stackoverflow.com/questions/988327/java-tail-f-wrapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!