Apache Util.copyStream:停止流

时间:2017-02-01 20:01:14

标签: java apache file-transfer

是否可以停止Apache Util.copyStream函数的bytesTransferred流?

long bytesTransferred = Util.copyStream(inputStream, outputStream, 32768, CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamListener() {
    @Override
    public void bytesTransferred(CopyStreamEvent event) {
        bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
    }
    @Override
    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                 long streamSize) {
        try {
            if(true) {
               log.info('Stopping');
               return; //Cancel
            } else {
              log.info('Still going');
            }

        } catch (InterruptedException e) {
            // this should not happen!
        }
    }
});

在这种情况下,会发生的事情是我在日志中不断收到Stopping消息。我也试过抛出一个新的RuntileException而不是返回,我再次得到无尽的Stopping消息。在这种情况下如何取消bytesTransfered?

1 个答案:

答案 0 :(得分:0)

您可以尝试包装输入流,并覆盖read方法以检查停止标志。如果设置,则抛出IOException。示例类。


/**
 * Wrapped input stream that can be cancelled.
 */
public class WrappedStoppableInputStream extends InputStream
{
    private InputStream m_wrappedInputStream;

    private boolean m_stop = false;

    /**
     * Constructor.
     * @param inputStream original input stream
     */
    public WrappedStoppableInputStream(InputStream inputStream)
    {
        m_wrappedInputStream = inputStream;
    }

    /**
     * Call to stop reading stream.
     */
    public void cancelTransfer()
    {
        m_stop = true;
    }


    @Override
    public int read() throws IOException
    {
        if (m_stop)
        {
            throw new IOException("Stopping stream");
        }

        return m_wrappedInputStream.read();
    }


    @Override
    public int read(byte[] b) throws IOException
    {
        if (m_stop)
        {
            throw new IOException("Stopping stream");
        }

        return m_wrappedInputStream.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException
    {
        if (m_stop)
        {
            throw new IOException("Stopping stream");
        }

        return m_wrappedInputStream.read(b, off, len);
    }
}

我假设文件复制在一个线程内运行。因此,您使用WrappedStoppableInputStream包装输入流,并将其传递给复制函数,以代替原始输入流使用。