Search code examples
javastreamoutputstreambytearrayoutputstream

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 ByteArrayOutputStream(100);
}

static int GetBufferSize(OutputStream out)
{
    return ( (ByteArrayOutputStream) out).size();
}


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?


Solution

  • 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();
    }