2017-02-01 2 views
0

Apache Util.copyStream関数のbytesTransferredストリームを停止することはできますか?Apache Util.copyStream:ストリームを停止する

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をスローしようとしました、そして、私は無限の停止メッセージを取得します。この場合、bytesTransferはどのように取り消しますか?

+0

彼のOPごとに、彼はそれを試みました。 – WillD

+0

例外をスローすることも同じことです。私は何度も何度もStoppingメッセージを受け取ります –

答えて

0

入力ストリームをラップし、読み込みメソッドをオーバーライドして停止フラグをチェックできます。設定されている場合は、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でラップし、コピー関数に渡して、元の入力ストリームの代わりに使用します。

関連する問題