tags:

views:

125

answers:

2

Is there an easy (therefore quick) way to accomplish this? Basically just take some input stream, could be something like a socket.getInputStream(), and have the stream's buffer autmoatically redirect to standard out?

+3  A: 

There are no easy ways to do it, because InputStream has a pull-style interface, when OutputStream has a push-style one. You need some kind of pumping loop to pull data from InputStream and push them into OutputStream. Something like this (run it in a separate thread if necessary):

int size = 0;
byte[] buffer = new byte[1024];
while ((size = in.read(buffer)) != -1) out.write(buffer, 0, size);

It's already implemented in Apache Commons IO as IOUtils.copy()

axtavt
Would Apache Common's IO tools help?
Zombies
@Zombies: Yes, you can use `IOUtils.copy()`
axtavt
@axtavt - As a general rule it is a bad idea to do byte-wise operations on an unbuffered stream. You may end up doing a system call for each call to `read(byte)` and `write(byte)`, and that is very expensive.
Stephen C
@Stephen: Yes, fixed
axtavt
copy(inputStream, System.out) ?
Zombies
@Zombies: Yes. And you should run it in a separate thread in you don't want to block your current thread
axtavt
+1  A: 

You need a simple thread which reads from the input stream and writes to standard output. Make sure it yields to other threads.

Draemon