jpayne@68: package fileIO; jpayne@68: jpayne@68: import java.io.IOException; jpayne@68: import java.io.InputStream; jpayne@68: import java.io.OutputStream; jpayne@68: jpayne@68: /** jpayne@68: * Listens to an output stream and copies it to an input stream. jpayne@68: * For example, redirects the error stream of some process to stderr. jpayne@68: * @author Brian Bushnell jpayne@68: * @date Jan 22, 2013 jpayne@68: * jpayne@68: */ jpayne@68: public class PipeThread extends Thread { jpayne@68: jpayne@68: // public PipeThread(InputStream is_){this(is_, System.err);} jpayne@68: jpayne@68: public PipeThread(InputStream is_, OutputStream os_){ jpayne@68: is=is_; jpayne@68: os=os_; jpayne@68: if(is==null){throw new RuntimeException("Null input stream.");} jpayne@68: if(os==null){throw new RuntimeException("Null output stream.");} jpayne@68: // synchronized(list){list.add(this);} jpayne@68: } jpayne@68: jpayne@68: @Override jpayne@68: public void run(){ jpayne@68: final byte[] buf=new byte[8196]; jpayne@68: try { jpayne@68: for(int len=is.read(buf); !finished && len>0; len=is.read(buf)){ jpayne@68: os.write(buf, 0, len); jpayne@68: } jpayne@68: } catch (IOException e) { jpayne@68: // TODO Auto-generated catch block jpayne@68: e.printStackTrace(); jpayne@68: } jpayne@68: jpayne@68: if(is!=System.in){ jpayne@68: try { jpayne@68: is.close(); jpayne@68: } catch (IOException e) { jpayne@68: // TODO Auto-generated catch block jpayne@68: e.printStackTrace(); jpayne@68: } jpayne@68: } jpayne@68: jpayne@68: if(os!=System.out && os!=System.err){ jpayne@68: ReadWrite.close(os); jpayne@68: } jpayne@68: jpayne@68: synchronized(this){ jpayne@68: finished=true; jpayne@68: this.notify(); jpayne@68: } jpayne@68: } jpayne@68: jpayne@68: public boolean finished(){ jpayne@68: synchronized(this){ jpayne@68: return finished; jpayne@68: } jpayne@68: } jpayne@68: jpayne@68: public void terminate(){ jpayne@68: synchronized(this){ jpayne@68: if(!finished){ jpayne@68: finished=true; jpayne@68: interrupt(); jpayne@68: } jpayne@68: } jpayne@68: } jpayne@68: jpayne@68: // public static void killList(){ jpayne@68: // System.err.println("Kill list."); jpayne@68: // synchronized(list){ jpayne@68: // for(PipeThread pt : list){ jpayne@68: // if(!pt.finished){ jpayne@68: // pt.terminate(); jpayne@68: // } jpayne@68: // } jpayne@68: // } jpayne@68: // } jpayne@68: jpayne@68: public final InputStream is; jpayne@68: public final OutputStream os; jpayne@68: private volatile boolean finished=false; jpayne@68: jpayne@68: // private static ArrayList list=new ArrayList(8); jpayne@68: jpayne@68: }