简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM