Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
Roman Avatar asked Apr 22 '15 08:04

Roman


1 Answers

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.

like image 52
Jayan Avatar answered Oct 06 '22 01:10

Jayan