Tail -f java shell

I need to wrap the Unix command "tail -f" in a BufferedInputStream. I do not want to imitate or imitate the tail, as indicated by this question . Rather, I want to use the tail, waiting for it to give me a new line.

+3
source share
6 answers

It is best to use the Process class and read using 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 be blocked, as it expects more input from the input stream, so you will not be busy reviving as the data arrives.

+14
source

Take a look at Runtime.exec (String command). Returns a Process object that has input and output streams.

+1
source

also check out ProcessBuilder :

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

where file is a string, for example, "/ var / log / messages".

+1
source

I assume that approaches like system () and popen () will not work, as they will block your program until the tail command completes.

I think you could redirect the output to a file and use "diff" for the latest version to see which lines are new?

0
source

If you have a unix command

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

Then the tail will appear as an InputStream , which can be locked for a certain period of time. If you do not want to block yourself, you should use nio packages. I find that most of the other ways to access the tail command (e.g. Process ) result in a similar InputStream .

0
source

All Articles