I'm having quite a problem here, and I think it is because I don't understand very much how I should use the API provided by Java.
I need to write an int
and a byte[]
into a byte[]
.
I thought of using a DataOutputStream
to solve the data writing with writeInt(int i)
and write(byte[] b)
, and to be able to put that into a byte array, I should use ByteArrayOutputStream
method toByteArray().
I understand that this classes use the Wrapper pattern, so I had two options:
DataOutputStream w = new DataOutputStream(new ByteArrayOutputStream());
or
ByteArrayOutputStream w = new ByteArrayOutputStream(new DataOutputStream());
but in both cases, I "loose" a method. in the first case, I can't access the toByteArray()
method, and in the second, I can't access the writeInt()
method.
How should I use this classes together?
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString() . Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.
Java DataOutputStream class methods It is used to return the number of bytes written to the data output stream. It is used to write the specified byte to the underlying output stream. It is used to write len bytes of data to the output stream. It is used to write Boolean to the output stream as a 1-byte value.
DataOutputStream Example write(45); //byte data dataOutputStream. writeInt(4545); //int data dataOutputStream. writeDouble(109.123); //double data dataOutputStream. close();
Like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream w = new DataOutputStream(baos);
w.writeInt(100);
w.write(byteArray);
w.flush();
byte[] result = baos.toByteArray();
Actually your second version will not work at all. DataOutputStream
requires an actual target stream in which to write the data. You can't do new DataOutputStream()
. There isn't actually any constructor like that.
Could you make a variable to hold on to the ByteArrayOutputStream and pass it into the DataOutputStream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(1);
byte[] result = dos.toByteArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With