Source code: com/jguild/jrpm/test/StreamGobbler.java
1 /*
2 * (c) C O P Y R I G H T 2001 by ASDIS Software AG Berlin
3 * ALL RIGHTS RESERVED
4 *
5 * $Id: StreamGobbler.java,v 1.2 2003/10/20 16:32:12 mkuss Exp $
6 *
7 */
8 package com.jguild.jrpm.test;
9
10 import java.io.*;
11
12
13 /**
14 * This class reads an input stream in an extra thread. This is
15 * used for running external programms out of java so that stdout
16 * and stderr are not blocking the process from work. If the
17 * stream is closed by Runtime the gobbler will also die.
18 *
19 * Usage:
20 * <code><pre>
21 * Process proc = Runtime.getRuntime().exec(command);
22 *
23 * // any error message?
24 * StreamGobbler errorGobbler = new StreamGobbler(rpmProc.getErrorStream(), System.err);
25 *
26 * // any output?
27 * StreamGobbler outputGobbler = new StreamGobbler(rpmProc.getInputStream(), System.out);
28 *
29 * // kick them off
30 * errorGobbler.start();
31 * outputGobbler.start();
32 * </pre></code>
33 *
34 * @author $author$
35 * @version $Revision: 1.2 $
36 */
37 public class StreamGobbler extends Thread {
38 InputStream is;
39 OutputStream os;
40
41 /**
42 * Creates a new StreamGobbler object for a given input stream
43 *
44 * @param is The input stream
45 */
46 public StreamGobbler(InputStream is) {
47 this(is, System.out);
48 }
49
50 /**
51 * Creates a new StreamGobbler object for a given input stream
52 * that will be redirected to the defined output stream.
53 *
54 * @param is The input stream
55 * @param redirect The output stream
56 */
57 public StreamGobbler(InputStream is, OutputStream redirect) {
58 this.is = is;
59 this.os = redirect;
60 }
61
62 /*
63 * @see java.lang.Runnable#run()
64 */
65 public void run() {
66 PrintWriter pw = null;
67
68 try {
69 pw = new PrintWriter(os);
70
71 InputStreamReader isr = new InputStreamReader(is);
72 BufferedReader br = new BufferedReader(isr);
73
74 String line = null;
75
76 while ((line = br.readLine()) != null) {
77 pw.println(line);
78 }
79
80 pw.flush();
81 } catch (IOException ioe) {
82 ioe.printStackTrace();
83 }
84
85 if (pw != null) {
86 pw.close();
87 }
88 }
89 }