Search code examples
javaio

Java: How do I pipe InputStream to standard out?


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?


Solution

  • 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()