Search code examples
javadataoutputstreambytearrayoutputstream

Passing ByteArrayOutputStream into the Constructor of DataOutputStream


I understand that this can be done using wrapper pattern, but i am having a hard time understanding, how does the following code work.

ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(bytearray);

passing ByteArrayOutputStream reference into the constructor of DataOutputStream means that the DataOutputStream gets converted to ByteArrayOutputStream, but how?

After this, os.writeUTF("String"); How does DataOutputStream convert to ByteArrayOutputStream.

What is happening behind the scenes? Can somebody please explain the details.


Solution

  • The DataOutputStream only requires any implementation of an OutputStream in its constructor. It doesn't care how it's implemented only that it satisfies the interface. A ByteArrayOutputStream provides an output stream backed by a byte array. Similarly, you could use a FileOutputStream to get a stream backed by a file on disk. From the DataOutputStream's perspective, they are both streams that used with an interface. OutputStream is a really simple interface, and just defines some methods that write byte arrays to some kind of storage device.

    There's no magic going on under the scenes, it just uses an OutputStream and doesn't care how it's implemented.