gpt4 book ai didi

java - 从输出流中获取输入流

转载 作者:搜寻专家 更新时间:2023-11-01 03:50:46 24 4
gpt4 key购买 nike

我有一个组件在输出流 (ByteArrayOutputStream) 中为我提供数据,我需要将其写入 SQL 数据库的 blob 字段而不创建临时缓冲区,因此需要获取输入溪流。

基于答案 herehere我想出了以下方法从输出流中获取输入流:

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);

关于java - 从输出流中获取输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com