Guest User

Untitled

a guest
Feb 26th, 2012
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. public class Piper implements java.lang.Runnable {
  2.  
  3. private java.io.InputStream input;
  4.  
  5. private java.io.OutputStream output;
  6.  
  7. public Piper(java.io.InputStream input, java.io.OutputStream output) {
  8. this.input = input;
  9. this.output = output;
  10. }
  11.  
  12. public void run() {
  13. try {
  14. // Create 512 bytes buffer
  15. byte[] b = new byte[512];
  16. int read = 1;
  17. // As long as data is read; -1 means EOF
  18. while (read > -1) {
  19. // Read bytes into buffer
  20. read = input.read(b, 0, b.length);
  21. //System.out.println("read: " + new String(b));
  22. if (read > -1) {
  23. // Write bytes to output
  24. output.write(b, 0, read);
  25. }
  26. }
  27. } catch (Exception e) {
  28. // Something happened while reading or writing streams; pipe is broken
  29. throw new RuntimeException("Broken pipe", e);
  30. } finally {
  31. try {
  32. input.close();
  33. } catch (Exception e) {
  34. }
  35. try {
  36. output.close();
  37. } catch (Exception e) {
  38. }
  39. }
  40. }
  41.  
  42. public static java.io.InputStream pipe(java.lang.Process... proc) throws java.lang.InterruptedException {
  43. // Start Piper between all processes
  44. java.lang.Process p1;
  45. java.lang.Process p2;
  46. for (int i = 0; i < proc.length; i++) {
  47. p1 = proc[i];
  48. // If there's one more process
  49. if (i + 1 < proc.length) {
  50. p2 = proc[i + 1];
  51. // Start piper
  52. new Thread(new Piper(p1.getInputStream(), p2.getOutputStream())).start();
  53. }
  54. }
  55. java.lang.Process last = proc[proc.length - 1];
  56. // Wait for last process in chain; may throw InterruptedException
  57. last.waitFor();
  58. // Return its InputStream
  59. return last.getInputStream();
  60. }
  61.  
  62. }
Add Comment
Please, Sign In to add comment