ringbuffer for ByteArrayOutputStream in java
i am looking for something like ByteArrayOutputStream but with limited size. 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.)
精彩评论