16

getPosition()ストリームの開始点から読み取ったバイト数を教えてくれる、汎用的で再利用可能なメソッドのようなものが欲しいです。理想的には、これがすべての InputStream で機能することを望みます。これにより、異なるソースから取得するときに、それらをすべてラップする必要がなくなります。

そのような獣は存在しますか?そうでない場合、誰かが count の既存の実装を推奨できますInputStreamか?

4

4 に答える 4

21

java.ioこれを実装するには、 で確立された Decorator パターンに従う必要があります。

ここで試してみましょう:

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public final class PositionInputStream
  extends FilterInputStream
{

  private long pos = 0;

  private long mark = 0;

  public PositionInputStream(InputStream in)
  {
    super(in);
  }

  /**
   * <p>Get the stream position.</p>
   *
   * <p>Eventually, the position will roll over to a negative number.
   * Reading 1 Tb per second, this would occur after approximately three 
   * months. Applications should account for this possibility in their 
   * design.</p>
   *
   * @return the current stream position.
   */
  public synchronized long getPosition()
  {
    return pos;
  }

  @Override
  public synchronized int read()
    throws IOException
  {
    int b = super.read();
    if (b >= 0)
      pos += 1;
    return b;
  }

  @Override
  public synchronized int read(byte[] b, int off, int len)
    throws IOException
  {
    int n = super.read(b, off, len);
    if (n > 0)
      pos += n;
    return n;
  }

  @Override
  public synchronized long skip(long skip)
    throws IOException
  {
    long n = super.skip(skip);
    if (n > 0)
      pos += n;
    return n;
  }

  @Override
  public synchronized void mark(int readlimit)
  {
    super.mark(readlimit);
    mark = pos;
  }

  @Override
  public synchronized void reset()
    throws IOException
  {
    /* A call to reset can still succeed if mark is not supported, but the 
     * resulting stream position is undefined, so it's not allowed here. */
    if (!markSupported())
      throw new IOException("Mark not supported.");
    super.reset();
    pos = mark;
  }

}

InputStreams はスレッドセーフであることを意図しているため、同期を自由に使用できます。volatile変数と位置変数をいじってみAtomicLongましたが、おそらく同期が最適です。これにより、1 つのスレッドがストリームを操作し、ロックを解放せずにその位置をクエリできるようになるからです。

PositionInputStream is = …
synchronized (is) {
  is.read(buf);
  pos = is.getPosition();
}
于 2008-10-27T16:05:15.273 に答える
15

CommonsIOパッケージのCountingInputStreamを見てください。他の便利なInputStreamバリアントのかなり良いコレクションもあります。

于 2008-10-27T17:31:35.990 に答える
2

いいえInputStream。潜在的に無限の量のデータを処理することを目的としているため、カウンターが邪魔になります。それらをすべてラップすることに加えて、アスペクトで何かできるかもしれません。

于 2008-10-27T15:29:23.770 に答える