nikk nikk - 4 months ago 13
Java Question

How to get the size of an empty "unwritten" stream?

I have an stream that is created with a fixed size. The buffer is empty.
I want to be able to get the size of this buffer. What is an efficient way of doing this?

Here is what I have done.

static OutputStream CreateBuffer()
{
return (OutputStream) new ByteArrayOutputStreamWithCapacity(100);
}

static int GetBufferSize(OutputStream out)
{
return ( (ByteArrayOutputStreamWithCapacity) out).capacity();
}


public static void main(String[] args)
{
System.out.println(GetBufferSize(CreateBuffer()));
}


I expect
100
. I know why it is 0 -- the stream was only allocated but nothing has actually been written to it yet. What is a good implementation to get the size of an empty outputstream without actually copying data?

Answer

You can get the internal buffer size by subclassing ByteArrayOutputStream:

private static class ByteArrayOutputStreamWithCapacity extends ByteArrayOutputStream {
    public ByteArrayOutputStreamWithCapacity(int size) {
        super(size);
    }

    public synchronized int capacity() {
        return buf.length;
    }
}

void CreateBuffer()
{
    OutputStream out = new ByteArrayOutputStreamWithCapacity(100);
}

int GetBufferSize(OutPutStream out)
{
    return ( (ByteArrayOutputStreamWithCapacity) out). capacity();
}