Why can you read data from an already closed ByteArrayOutputStream?

I am wondering why you can still read bytes from an already closed ByteArrayOutputStream . Doesn't this line of documents mean the opposite?

public void close () : Closes this stream. This frees up the system resources used for this thread.

Code example:

 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?

+6
source share
1 answer

ByteArrayOutputStream.toByteArray just copies what it has in the buffer; he does not read anything 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 is not affected. Methods in this class can be called after the thread has been closed without throwing an IO exception.

 public void close() throws IOException { } 

close() does nothing.

+5
source

Source: https://habr.com/ru/post/985659/


All Articles