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?
Could you make a variable to hold on to the ByteArrayOutputStream and pass it into the DataOutputStream.
Like this:
Actually your second version will not work at all.
DataOutputStream
requires an actual target stream in which to write the data. You can't donew DataOutputStream()
. There isn't actually any constructor like that.You don´t need more like this
Use the former case - wrap
DataOutputStream
around theByteArrayOutputStream
. Just make sure you save the reference to theByteArrayOutputStream
. When you are finish close() or at least flush() theDataOutputStream
and then use the toByteArray method of theByteArrayOutputStream
.You could use a stream approach if you connect your outputstream to an inputstream through a
PipedInputStream
/PipetOutputStream
. Then you will consume the data from the inputstream.Anyway if what you need to do is simple and doesn't not require a stream approach I would use a
java.nio.ByteBuffer
on which you haveput(byte[] src)
for yourbyte[]
putInt(int value)
byte[] array()
to get the contentThe Integer class has a method to get the byte value of an int.
Integer.byteValue()