1 26 27 package net.sourceforge.groboutils.util.thread.v1; 28 29 30 import java.io.IOException ; 31 import java.io.InputStream ; 32 import java.io.OutputStream ; 33 34 35 44 public class IOThreadRunner 45 { 46 private static final int BUFFER_SIZE = 4096; 47 private InputStream is; 48 private OutputStream os; 49 private byte[] buffer = new byte[ BUFFER_SIZE ]; 50 private LoopThread lt; 51 private IOException exception; 52 private boolean closeInputOnEOF = false; 53 private boolean closeOutputOnEOF = false; 54 55 private Runnable ltRunner = new Runnable () 56 { 57 public void run() 58 { 59 try 60 { 61 int read = is.read( buffer, 0, BUFFER_SIZE ); 62 if (read > 0) 63 { 64 69 os.write( buffer, 0, read ); 70 } 71 else 72 { 73 reachedEOF(); 75 } 76 } 77 catch (IOException e) 78 { 79 registerException( e ); 80 } 81 } 82 }; 83 84 88 public IOThreadRunner( InputStream is, OutputStream os ) 89 { 90 this( new LoopThread(), is, os ); 91 92 this.lt.setDaemon( true ); 93 this.lt.setSleepTimeMillis( 0L ); 94 } 95 96 97 102 public IOThreadRunner( LoopThread lt, InputStream is, OutputStream os ) 103 { 104 this.lt = lt; 105 lt.setRunnable( ltRunner ); 106 this.is = is; 107 this.os = os; 108 } 109 110 111 115 public IOException getException() 116 { 117 return this.exception; 118 } 119 120 121 125 public void setCloseInputOnStop( boolean on ) 126 { 127 this.closeInputOnEOF = on; 128 } 129 130 131 135 public void setCloseOutputOnStop( boolean on ) 136 { 137 this.closeOutputOnEOF = on; 138 } 139 140 141 146 public LoopThread getThread() 147 { 148 return this.lt; 149 } 150 151 152 155 public OutputStream getOutputStream() 156 { 157 return this.os; 158 } 159 160 161 165 public boolean isReading() 166 { 167 return this.lt.isAlive(); 168 } 169 170 171 174 public void start() 175 { 176 this.lt.start(); 177 } 178 179 180 183 public void stop() 184 throws IOException 185 { 186 if (this.closeInputOnEOF) 187 { 188 this.is.close(); 189 } 190 if (this.closeOutputOnEOF) 191 { 192 this.os.close(); 193 } 194 this.lt.stop(); 195 } 196 197 198 201 protected void registerException( IOException ioe ) 202 { 203 this.exception = ioe; 204 try 205 { 206 stop(); 207 } 208 catch (IOException ex) 209 { 210 } 212 } 213 214 215 218 protected void reachedEOF() 219 { 220 this.exception = null; 221 try 222 { 223 stop(); 224 } 225 catch (IOException ioe) 226 { 227 this.exception = ioe; 228 } 229 } 230 } 231 | Popular Tags |