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