Skip to content

Instantly share code, notes, and snippets.

@rbe
Created October 22, 2010 07:23
Show Gist options
  • Save rbe/640092 to your computer and use it in GitHub Desktop.
Save rbe/640092 to your computer and use it in GitHub Desktop.
public class Piper implements java.lang.Runnable {
private java.io.InputStream input;
private java.io.OutputStream output;
public Piper(java.io.InputStream input, java.io.OutputStream output) {
this.input = input;
this.output = output;
}
public void run() {
try {
// Create 512 bytes buffer
byte[] b = new byte[512];
int read = 1;
// As long as data is read; -1 means EOF
while (read > -1) {
// Read bytes into buffer
read = input.read(b, 0, b.length);
//System.out.println("read: " + new String(b));
if (read > -1) {
// Write bytes to output
output.write(b, 0, read);
}
}
} catch (Exception e) {
// Something happened while reading or writing streams; pipe is broken
throw new RuntimeException("Broken pipe", e);
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
}
}
public static java.io.InputStream pipe(java.lang.Process... proc) throws java.lang.InterruptedException {
// Start Piper between all processes
java.lang.Process p1;
java.lang.Process p2;
for (int i = 0; i < proc.length; i++) {
p1 = proc[i];
// If there's one more process
if (i + 1 < proc.length) {
p2 = proc[i + 1];
// Start piper
new Thread(new Piper(p1.getInputStream(), p2.getOutputStream())).start();
}
}
java.lang.Process last = proc[proc.length - 1];
// Wait for last process in chain; may throw InterruptedException
last.waitFor();
// Return its InputStream
return last.getInputStream();
}
}
public class PipeTest {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
java.lang.Runtime rt = java.lang.Runtime.getRuntime();
// Start three processes: ps ax | grep rbe | grep JavaVM
java.lang.Process p1 = rt.exec("ps ax");
java.lang.Process p2 = rt.exec("grep rbe");
java.lang.Process p3 = rt.exec("grep JavaVM");
// Start piping
java.io.InputStream in = Piper.pipe(p1, p2, p3);
// Show output of last process
java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(in));
String s = null;
while ((s = r.readLine()) != null) {
System.out.println(s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment