Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Created June 14, 2015 08:44
Show Gist options
  • Save jarrodhroberson/544d1417e868fcfcc99b to your computer and use it in GitHub Desktop.
Save jarrodhroberson/544d1417e868fcfcc99b to your computer and use it in GitHub Desktop.
How to use PipedInputStream and PipedOutputStream
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedInputOutputStreams
{
public static void main(String[] args)
{
try
{
final PipedOutputStream pos = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(pos);
final InputStream is = PipedInputOutputStreams.class.getClassLoader().getResourceAsStream("logback.xml");
final Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
try { ByteStreams.copy(is, pos); }
catch (IOException e) { throw new RuntimeException(e); }
finally
{
try { is.close(); } catch (final IOException e) { System.err.println(e.getMessage()); }
try { pos.close(); } catch (final IOException e) { System.err.println(e.getMessage()); }
}
}
});
t.start();
ByteStreams.copy(pis, System.out);
pis.close();
t.join();
}
catch (IOException | InterruptedException e) { throw new RuntimeException(e); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment