从输出流中获取输入流 [英] Get an input stream from an output stream
问题描述
我有一个在输出流(ByteArrayOutputStream
)中给我数据的组件,我需要将其写入SQL数据库的blob字段中而不创建临时缓冲区,因此需要获取输入流.
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);
}
}
}
请注意,输出流已经包含写入的数据,并且可以运行1-2 MB.
但是,无论尝试在两个单独的线程中还是在同一线程中执行此操作,我都会发现总是PipedInputStream
挂在以下位置:
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
推荐答案
您正在使解决方案过于复杂
You are overcomplicating the solution
ByteArrayOutputStream baos = ...;
byte[] data = baos.toByteArray();
return new ByteArrayInputStream(data);
这篇关于从输出流中获取输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!