I have a component that's given me data in an output stream (ByteArrayOutputStream
) and I need to write this into a blob field of a SQL database without creating temp buffers hence the need to get an input stream.
Based on answers here and here I came up the following method to get an input stream from an output stream:
private PipedInputStream getInputStream(ByteArrayOutputStream outputStream) throws InterruptedException
{
PipedInputStream pipedInStream = new PipedInputStream();
Thread copyThread = new Thread(new CopyStreamHelper(outputStream, pipedInStream));
copyThread.start();
// Wait for copy to complete
copyThread.join();
return pipedInStream;
}
class CopyStreamHelper implements Runnable
{
private ByteArrayOutputStream outStream;
private PipedInputStream pipedInStream;
public CopyStreamHelper (ByteArrayOutputStream _outStream, PipedInputStream _pipedInStream)
{
outStream = _outStream;
pipedInStream = _pipedInStream;
}
public void run()
{
PipedOutputStream pipedOutStream = null;
try
{
// write the original OutputStream to the PipedOutputStream
pipedOutStream = new PipedOutputStream(pipedInStream);
outStream.writeTo(pipedOutStream);
}
catch (IOException e)
{
// logging and exception handling should go here
}
finally
{
IOUtils.closeQuietly(pipedOutStream);
}
}
}
Please note that the output stream already contains the written data and it can run up to 1-2 MB.
However regardless of trying to do this in two separate threads or the same thread I am finding that always PipedInputStream
hangs at the following:
Object.wait(long) line: not available [native method]
PipedInputStream.awaitSpace() line: not available