KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SnowMailClient > utils > StreamGobbler


1 package SnowMailClient.utils;
2
3
4
5 import java.util.*;
6 import java.io.*;
7
8 public class StreamGobbler extends Thread JavaDoc
9 {
10     private InputStream inputStream;
11     private OutputStream outputStream;
12
13     private String JavaDoc streamIdentifier = "";
14     // Is just a text, which is repeated on each beginning of a line.
15

16
17
18    /**
19     * Constructor 1.
20     * The outputStream can be null - then the input just will be
21     * read, but not forwarded.
22     */

23     public StreamGobbler( final InputStream inputStream,
24                           final OutputStream outputStream )
25     {
26       this.inputStream = inputStream;
27       this.outputStream = outputStream;
28     }
29
30
31
32    /**
33     * Constructor 2: An additional name is passed, which is
34     * written out on each beginning of a line.
35     * The outputStream can be null - then the input just will be
36     * read, but not forwarded.
37     */

38     public StreamGobbler( final InputStream inputStream,
39                           final OutputStream outputStream,
40                           final String JavaDoc theStreamIdentifier)
41     {
42       this(inputStream,outputStream);
43       this.streamIdentifier = theStreamIdentifier + "> ";
44     }
45
46
47
48     public void run()
49     {
50       try
51        {
52          PrintWriter printWriter = null;
53          if( this.outputStream != null ) printWriter = new PrintWriter(this.outputStream);
54          final InputStreamReader isr = new InputStreamReader(this.inputStream);
55          final BufferedReader br = new BufferedReader(isr);
56          String JavaDoc line = null;
57          while( (line = br.readLine()) != null)
58          {
59            if( printWriter != null )
60            {
61                printWriter.println( this.streamIdentifier + line );
62                //System.out.println("Debug: "+line);
63
printWriter.flush();
64            } // else we do nothing
65
}
66        }
67       catch( IOException ioe )
68        {
69          ioe.printStackTrace();
70        }
71     } //run
72

73
74
75 } // StreamGobbler
Popular Tags