我有一个组件在输出流中为我提供数据(ByteArrayOutputStream
)并且我需要将其写入 SQL 数据库的 blob 字段而不创建临时缓冲区,因此需要获取输入流。
根据答案here https://stackoverflow.com/questions/5778658/java-converting-from-outputstream-to-inputstream and here https://stackoverflow.com/questions/1225909/most-efficient-way-to-create-inputstream-from-outputstream我想出了以下方法从输出流获取输入流:
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
您使解决方案过于复杂
ByteArrayOutputStream baos = ...;
byte[] data = baos.toByteArray();
return new ByteArrayInputStream(data);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)