Search code examples
javajava-iobytearrayoutputstream

Why you can read data from already closed ByteArrayOutputStream?


I'm wondering why you still can read bytes from already closed ByteArrayOutputStream. Doesn't this line from docs mean the opposite?

public void close (): Closes this stream. This releases system resources used for this stream.

Sample code:

String data = "Some string ...";
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
dOut.write(data.getBytes());
dOut.close();
System.out.println("Length: " + bOut.toByteArray().length);
System.out.println("Byte #2: " + bOut.toByteArray()[2]);

Output:

Length: 15
Byte #2: 109

Am I doing something wrong?


Solution

  • ByteArrayOutputStream.toByteArray just copies what it has in the buffer; it's not reading anything more from the stream.

    public synchronized byte[] toByteArray() {
        return Arrays.copyOf(buf, count);
    }
    

    Also this class is a bit special. See Java documentation and code.

    Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

    public void close() throws IOException {
    }
    

    close() does not really do anything.