views:

100

answers:

1

hi 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?

+2  A: 

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.)

aioobe
Thanks, exactly what i needed. I just wondered if i am the only one how is in need for such a thing? Doesn't seem to exotic to me.
Martin
Have you searched for "java ringbuffer" on google? There are tons of implementations.
aioobe