gpt4 book ai didi

java - 给定 Java InputStream,如何确定流中的当前偏移量?

转载 作者:太空狗 更新时间:2023-10-29 23:01:00 28 4
gpt4 key购买 nike

我想要一个通用的、可重复使用的 getPosition() 方法,它会告诉我从流的起点读取的字节数。理想情况下,我希望它能与所有 InputStreams 一起使用,这样我就不必在从不同来源获取它们时包装它们中的每一个。

这样的野兽存在吗?如果没有,谁能推荐一个现有的计数 InputStream 实现?

最佳答案

您需要遵循 java.io 中建立的装饰器模式来实现它。

让我们在这里试一试:

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 旨在实现线程安全,因此可以自由使用同步。我试过 volatileAtomicLong 位置变量,但同步可能是最好的,因为它允许一个线程在流上操作并查询其位置而不放弃锁。

PositionInputStream is = …
synchronized (is) {
is.read(buf);
pos = is.getPosition();
}

关于java - 给定 Java InputStream,如何确定流中的当前偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/240294/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com