Java Apache Util.copyStream:停止流

Java Apache Util.copyStream:停止流,java,apache,file-transfer,Java,Apache,File Transfer,是否可以停止Apache Util.copyStream函数的ByTestTransferred流 long bytesTransferred = Util.copyStream(inputStream, outputStream, 32768, CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamListener() { @Override public void bytesTransferred(CopyStreamEvent

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

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

在这种情况下,我会在日志中不断收到停止消息。我还尝试抛出一个新的RuntileException而不是返回,并且再次收到无休止的停止消息。在这种情况下,如何取消ByTestTransfer?

您可以尝试包装输入流,并重写读取方法以检查停止标志。如果已设置,则抛出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); } } /** *可取消的已包装输入流。 */ 公共类wrappedStatableInputStream扩展了InputStream { 私有输入流m_wrappedInputStream; 私有布尔m_stop=false; /** *构造器。 *@param inputStream原始输入流 */ public WrappedStoppableInputStream(InputStream InputStream) { m_wrappedInputStream=输入流; } /** *调用以停止读取流。 */ 公开转让 { m_stop=true; } @凌驾 public int read()引发IOException { 如果(m_停止) { 抛出新IOException(“停止流”); } 返回m_wrappedInputStream.read(); } @凌驾 公共整数读取(字节[]b)引发IOException { 如果(m_停止) { 抛出新IOException(“停止流”); } 返回m_wrappedInputStream.read(b); } @凌驾 公共整数读取(字节[]b,整数关闭,整数长度)引发IOException { 如果(m_停止) { 抛出新IOException(“停止流”); } 返回m_wrappedInputStream.read(b,off,len); } }
我假设文件复制在线程内运行。因此,使用WrappedStoppableInputStream包装输入流,并将其传递给复制函数,以替代原始输入流

根据他的操作,他确实尝试过。抛出异常也会做同样的事情。我会一遍又一遍地听到停止的信息