tags:

views:

876

answers:

5

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  A: 

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

Gandalf
This seems like what I'm looking for. I'll be trying this, thanks.
geowa4
No problem, feel free to upvote it ;)
Gandalf
A: 

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?

vext01
A: 

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.

Kathy Van Stone
+8  A: 

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.

mustpax
Thanks! It works very well.
geowa4
The only problem is that it requires a new line character at the end
geowa4
+1  A: 

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".

dfa