> public class StreamConsumer extends Thread
public class StreamConsumer implements Runnable
BTW, the "consumer" does not consume the stream, but copies it to
standard out. Probably another class name would be better.
> {
> protected BufferedInputStream stream;
> protected int bufSize = 1024;
protected static final int BUF_SIZE = 1024;
> protected byte[] buffer;
Why delay the allocation of the buffer memory?
protected byte buffer[] = new byte[BUF_SIZE];
> public StreamConsumer(InputStream stream)
> {
> this.stream = new BufferedInputStream(stream);
> buffer = new byte[bufSize];
If you have an own buffer, there is no point in wrapping the stream in
an extra BufferedInputStream. One buffer is enough.
> }
>
[quoted text clipped - 6 lines]
> {
> int count = stream.read(buffer, 0, bufSize);
BufferedInputStream.read() tries to avoid blocking by checking the
available() method of the underlying stream and returning early if there
is no data available. Depending on the behavior of the underlying
stream, you have just implemented a CPU-cycle burning while() loop.
[I have not checked the behavior of the streams returned by Process.
Maybe their available() methods always return available() == true, even
if no data is there, which would result in a blocking read()]
> String out = new String(buffer);
> System.out.print(out);
System.out is a PrintStream. You can directly copy the read bytes out,
without the need to convert to a String. See the write() method.
Also, if you use this for the output from a child process, you are
redirecting data from standard out and standard error from the child
process to standard out only. This breaks many useful applications.
> if ( count < 0 )
> {
[quoted text clipped - 7 lines]
> }
> }
I would store the exception, so the creator of the thread could have a
look at it later.
> /** A class that prints something to stderr. */
But which your code redirects to standard out.
/Thomas

Signature
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
rwfields@yahoo.com - 17 Feb 2006 23:07 GMT
Thanks Thomas. I always appreciate intelligent feedback.
R