我有一个在输出流中向我提供数据的组件(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);

09-26 12:42