[英]ringbuffer for ByteArrayOutputStream in java
i am looking for something like ByteArrayOutputStream but with limited size. 我正在寻找类似ByteArrayOutputStream的东西,但大小有限。 If size is exceeded older data should be overwritten. 如果超出大小,则旧数据应被覆盖。 That is as far as i understand a ringbuffer. 据我所知,这是一个环形缓冲区。 Any ideas? 有任何想法吗?
There's not really much to it. 其实没有太多。 You could do it yourself. 你可以自己做。 Here is a start: 这是一个开始:
class ByteArrayRingBuffer extends OutputStream {
byte[] data;
int capacity, pos = 0;
boolean filled = false;
public ByteArrayRingBuffer(int capacity) {
data = new byte[capacity];
this.capacity = capacity;
}
@Override
public synchronized void write(int b) {
if (pos == capacity) {
filled = true;
pos = 0;
}
data[pos++] = (byte) b;
}
public byte[] toByteArray() {
if (!filled)
return Arrays.copyOf(data, pos);
byte[] ret = new byte[capacity];
System.arraycopy(data, pos, ret, 0, capacity - pos);
System.arraycopy(data, 0, ret, capacity - pos, pos);
return ret;
}
}
(You may want to override write(byte[] b, int off, int len)
if you need the efficiency.) (如果需要效率write(byte[] b, int off, int len)
您可能需要重写write(byte[] b, int off, int len)
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.