Skip to content

Instantly share code, notes, and snippets.

@lindenb
Created March 24, 2014 15:35
Show Gist options
  • Save lindenb/9742643 to your computer and use it in GitHub Desktop.
Save lindenb/9742643 to your computer and use it in GitHub Desktop.
import java.io.*;
class Test
{
private static class Source
implements Runnable
{
private PipedOutputStream pipedOutputStream=new PipedOutputStream();
private InputStream in;
Source(InputStream in) throws IOException
{
this.in=in;
}
@Override
public void run()
{
try
{
int c;
while((c=this.in.read())!=-1)
{
pipedOutputStream.write(c);
}
pipedOutputStream.flush();
pipedOutputStream.close();
}
catch(Exception err)
{
err.printStackTrace();
}
}
}
private static class Grep
implements Runnable
{
private PipedInputStream pipeInPipedInputStream;
public Grep(Source src) throws IOException
{
this.pipeInPipedInputStream=new PipedInputStream(src.pipedOutputStream);
}
@Override
public void run()
{
try {
Process proc=Runtime.getRuntime().exec(new String[]{
"/bin/grep",
"A"});
OutputStream os=proc.getOutputStream();
Thread t1=new Thread(new CopyTo(proc.getErrorStream(),System.err));
Thread t2=new Thread(new CopyTo(proc.getInputStream(),System.out));
t1.start();
t2.start();
int c;
while((c=this.pipeInPipedInputStream.read())!=-1)
{
os.write((char)c);
}
t1.join();
t2.join();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private static class CopyTo implements Runnable
{
private InputStream in;
private OutputStream out;
CopyTo(InputStream in,OutputStream out)
{
this.in=in;
this.out=out;
}
@Override
public void run() {
try {
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
try
{
Source src=new Source(System.in);
Thread t1=new Thread(src);
Thread t2=new Thread(new Grep(src));
t1.start();
t2.start();
}
catch(Exception err)
{
err.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment