Skip to content

Instantly share code, notes, and snippets.

@yuka2py
Created February 18, 2014 22:32
Show Gist options
  • Save yuka2py/9081833 to your computer and use it in GitHub Desktop.
Save yuka2py/9081833 to your computer and use it in GitHub Desktop.
InputStream の流量を監視する MonitorInputStream と そのリスナー
package jp.foreignkey.java.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* データの流量を監視する InputStream
* 監視には、MonitorInputStreamListener を利用する。
*
* @author yuka2py
*/
public class MonitorInputStream
extends FilterInputStream
implements MonitorInputStreamListener {
private MonitorInputStreamListener mListener;
private InputStream mOriginalStream;
public MonitorInputStream(InputStream in) {
super(in);
mOriginalStream = in;
mListener = this;
}
/**
* オリジナルのストリームを取得する
*
* @return
*/
public InputStream getOriginalStream() {
return mOriginalStream;
}
@Override
public void onStreamEnd(MonitorInputStream stream) {
}
@Override
public void onStreamRead(int size, MonitorInputStream stream) {
}
protected void publishProgress(int read) {
if (0 < read) {
mListener.onStreamRead(read, this);
} else if (-1 == read) {
mListener.onStreamEnd(this);
}
}
@Override
public int read() throws IOException {
int size = super.read();
publishProgress(size);
return size;
}
@Override
public int read(byte[] b) throws IOException {
int size = super.read(b);
publishProgress(size);
return size;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int size = super.read(b, off, len);
publishProgress(size);
return size;
}
/**
* リスナーをセットする
*
* @param listener
*/
public void setStreamMonitor(MonitorInputStreamListener listener) {
mListener = listener;
}
}
package jp.foreignkey.java.io;
/**
* ストリームの流量をモニターする為のインターフェース
*
* @author yuka2py
*/
public interface MonitorInputStreamListener {
/**
* 読み込みの終了を通知
*/
public void onStreamEnd(MonitorInputStream stream);
/**
* 読み込みされたサイズを通知
*
* @param read 今回読み込まれたサイズ
*/
public void onStreamRead(int read, MonitorInputStream stream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment