我有一个组件,它给我提供了一个输出流(
基于这里和这里的答案,我想到了以下方法来从输出流获取输入流:
请注意,输出流已经包含写入的数据,并且可以运行达到1-2 MB。但是,无论是尝试在两个单独的线程中执行此操作还是在同一个线程中执行此操作,我发现
ByteArrayOutputStream
)中的数据,我需要将其写入SQL数据库的blob字段中,而不创建临时缓冲区,因此需要获取输入流。基于这里和这里的答案,我想到了以下方法来从输出流获取输入流:
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);
}
}
}
请注意,输出流已经包含写入的数据,并且可以运行达到1-2 MB。但是,无论是尝试在两个单独的线程中执行此操作还是在同一个线程中执行此操作,我发现
PipedInputStream
总是在以下位置挂起:Object.wait(long) line: not available [native method]
PipedInputStream.awaitSpace() line: not available