public abstract class PumpedInputStream extends PipedInputStream implements Runnable
PipedInputStream and PipedOutputStream
Using PipedInputStream and PipedOutputStream looks cumbersome.
PipedInputStream pipedIn = new PipedInputStream();
final PipedOutputStream pipedOut = new PipedOutputStream(pipedIn);
final IOException ioEx[] = { null };
new Thread(){
@Override
public void run(){
try{
writeDataTo(pipedOut);
pipedOut.close();
}catch(IOException ex){
ioEx[0] = ex;
}
}
}.start();
readDataFrom(pipedIn);
pipedIn.close();
if(ioEx[0]!=null)
throw new RuntimeException("something gone wrong", ioEx[0]);
The same can be achieved using PumpedInputStream as follows:
PumpedInputStream in = new PumpedInputStream(){
@Override
protected void pump(PipedOutputStream out) throws Exception{
writeDataTo(out);
}
}.start(); // start() will spawn new thread
readDataFrom(in);
in.close(); // any exceptions occurred in pump(...) are thrown by close()
PumpedInputStream is an abstract class with following abstract method:
protected abstract void pump(PipedOutputStream out) throws Exception;
This method implementation should write data into out which is passed as argument and close it.pump(...) are wrapped in IOException and rethrown by PumpedReader.close().
PumpedInputStream implements Runnable which is supposed to be run in thread.
You can use PumpedInputStream.start() method to start thread or spawn thread implicitly.
start() method returns self reference.
public PumpedInputStream start();
The advantage of PumpedInputStream over PipedInputStream/PipedOutputStream/Thread is:
PumpedReaderbuffer, in, PIPE_SIZE| Constructor and Description |
|---|
PumpedInputStream() |
| Modifier and Type | Method and Description |
|---|---|
void |
close()
Closes this stream and releases any system resources
associated with the stream.
|
protected abstract void |
pump(PipedOutputStream out)
Subclasse implementation should write data into
writer. |
void |
run() |
PumpedInputStream |
start()
Starts a thread with this instance as runnable.
|
mark, markSupported, read, reset, skippublic PumpedInputStream start()
public void close()
throws IOException
Any exception thrown by pump(java.io.PipedOutputStream)
are cached and rethrown by this method
close in interface Closeableclose in interface AutoCloseableclose in class PipedInputStreamIOException - if an I/O error occurs.protected abstract void pump(PipedOutputStream out) throws Exception
writer.out - outputstream into which data should be writtenExceptionCopyright © 2021. All rights reserved.