001    package edu.rice.cs.cunit.util;
002    
003    import java.io.*;
004    
005    /**
006     * StreamRedirectThread is a thread which copies its input to its output and terminates when it completes.
007     *
008     * @author Mathias Ricken
009     */
010    public class StreamRedirectThread extends Thread {
011        /// Input reader
012        private final Reader in;
013    
014        /// Output writer
015        private final Writer out;
016    
017        /// Data buffer size
018        private static final int BUFFER_SIZE = 2048;
019    
020        /**
021         * Constructor
022         *
023         * @param name thread name
024         * @param in   stream to copy from
025         * @param out  stream to copy to
026         */
027        public StreamRedirectThread(String name, InputStream in, OutputStream out) {
028            super(name);
029            this.in = new InputStreamReader(in);
030            this.out = new OutputStreamWriter(out);
031            setPriority(Thread.MAX_PRIORITY - 1);
032            setDaemon(true);
033        }
034    
035        /**
036         * Copy.
037         */
038        public void run() {
039            try {
040                char[] cbuf = new char[BUFFER_SIZE];
041                int count;
042                while ((count = in.read(cbuf, 0, BUFFER_SIZE)) >= 0) {
043                    out.write(cbuf, 0, count);
044                    out.flush();
045                }
046                out.flush();
047            }
048            catch (IOException exc) {
049                System.err.println("Child I/O Transfer - " + exc);
050            }
051        }
052    }