1 18 19 package org.apache.tools.ant.taskdefs; 20 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.io.OutputStream ; 24 25 30 public class StreamPumper implements Runnable { 31 32 private InputStream is; 33 private OutputStream os; 34 private volatile boolean finish; 35 private volatile boolean finished; 36 private boolean closeWhenExhausted; 37 private boolean autoflush = false; 38 private Exception exception = null; 39 private int bufferSize = 128; 40 private boolean started = false; 41 42 50 public StreamPumper(InputStream is, OutputStream os, 51 boolean closeWhenExhausted) { 52 this.is = is; 53 this.os = os; 54 this.closeWhenExhausted = closeWhenExhausted; 55 } 56 57 63 public StreamPumper(InputStream is, OutputStream os) { 64 this(is, os, false); 65 } 66 67 72 void setAutoflush(boolean autoflush) { 73 this.autoflush = autoflush; 74 } 75 76 81 public void run() { 82 synchronized (this) { 83 started = true; 84 } 85 finished = false; 86 finish = false; 87 88 final byte[] buf = new byte[bufferSize]; 89 90 int length; 91 try { 92 while ((length = is.read(buf)) > 0 && !finish) { 93 os.write(buf, 0, length); 94 if (autoflush) { 95 os.flush(); 96 } 97 } 98 os.flush(); 99 } catch (Exception e) { 100 synchronized (this) { 101 exception = e; 102 } 103 } finally { 104 if (closeWhenExhausted) { 105 try { 106 os.close(); 107 } catch (IOException e) { 108 } 110 } 111 finished = true; 112 synchronized (this) { 113 notifyAll(); 114 } 115 } 116 } 117 118 122 public boolean isFinished() { 123 return finished; 124 } 125 126 131 public synchronized void waitFor() 132 throws InterruptedException { 133 while (!isFinished()) { 134 wait(); 135 } 136 } 137 138 143 public synchronized void setBufferSize(int bufferSize) { 144 if (started) { 145 throw new IllegalStateException ( 146 "Cannot set buffer size on a running StreamPumper"); 147 } 148 this.bufferSize = bufferSize; 149 } 150 151 155 public synchronized int getBufferSize() { 156 return bufferSize; 157 } 158 159 163 public synchronized Exception getException() { 164 return exception; 165 } 166 167 174 synchronized void stop() { 175 finish = true; 176 notifyAll(); 177 } 178 } 179 | Popular Tags |