7

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?

maba
  • 47,113
  • 10
  • 108
  • 118
Roman
  • 898
  • 1
  • 10
  • 24

1 Answers1

6

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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Jayan
  • 18,003
  • 15
  • 89
  • 143
  • Okay, thank you. I thought close() should flush underlying buf. But it seems like it doesn't – Roman Apr 22 '15 at 08:42