This question already has an answer here:
How can I get the bytes of an outputStream, or how can I convert an outputStream to a byte array?
This question already has an answer here:
How can I get the bytes of an outputStream, or how can I convert an outputStream to a byte array?
From a theoretical perspective (i.e., irrespective of whether it makes sense in practice as a use case), this is an interesting question that essentially requires the implementation of a method like
The
Java
OutputStream
class, as its name implies, only supports an overriddenwrite()
method for I/O, and thatwrite()
method gets either an integer (representing 1 byte) or abyte
array, the contents of which it sends to an output (e.g., a file).For example, the following code saves the bytes already present in the
data
array, to theoutput.txt
file:In order to get all the data that a given
OutputStream
will be outputting and put it into abyte
array (i.e., into abyte[]
object), the class from which the correspondingOutputStream
object was instantiated, should keep storing all the bytes processed via itswrite()
methods and provide a special method, such astoByteArray()
, that would return them all, upon invocation.This is exactly what the
ByteArrayOutputStream
class does, making theconvert()
method trivial (and unnecessary):For any other type of
OutputStream
, not inherently supporting a similar conversion to abyte[]
object, there is no way to make the conversion, before theOutputStream
is drained, i.e. before the desired calls to itswrite()
methods have been completed.If such an assumption (of the writes to have been completed) can be made, and if the original
OutputStream
object can be replaced, then one option is to wrap it inside a delegate class that would essentially "grab" the bytes that would be supplied via itswrite()
methods. For example:The calls to the
write()
methods of the internal "buffer" (ByteArrayOutputStream
) precede the calls to the original stream (which, in turn, can be accessed viasuper
, or even viathis.out
, since the corresponding parameter of theFilterOutputStream
isprotected
). This makes sure that the bytes will be buffered, even if there is an exception while writing to the original stream.To reduce the overhead, the calls to
super
in the above class can be omitted - e.g., if only the "conversion" to abyte
array is desired. Even theByteArrayOutputStream
orOutputStream
classes can be used as parent classes, with a bit more work and some assumptions (e.g., about thereset()
method).In any case, enough memory has to be available for the draining to take place and for the
toByteArray()
method to work.For @Obicere comment example: