public byte[] toByteArray() {
try {
ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(objectStream);
dout.writeUTF(recordid);
dout.close();
objectStream.close();
return objectStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).
edit: My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?
public byte[] toByteArray() {
try {
ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(realOutputStream);
dout.writeUTF(dataObject.getClass().toString());
dout.writeUTF(recordid);
System.out.println("Recordid: " + recordid + "|" + dout.hashCode());
dout.flush();
System.out.println("Recordid: " + recordid + "|" + dout.hashCode());
ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
dout.write(objectStream.toByteArray());
dout.close();
objectStream.close();
return objectStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
The concat() method of Bytes Class in the Guava library is used to concatenate the values of many arrays into a single array. These byte arrays to be concatenated are specified as parameters to this method. returns the array {1, 2, 3, 4, 5, 6, 7}.
The recommended solution to concatenate two or more byte arrays is using ByteArrayOutputStream . The idea is to write bytes from each of the byte arrays to the output stream, and then call toByteArray() to get the current contents of the output stream as a byte array.
The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
To write the data to the output stream, we have used the write() method. Note: The getBytes() method used in the program converts a string into an array of bytes.
try the following to place the recordid first.
ByteArrayOutputStream objectStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(objectStream);
dout.writeUTF(recordid);
dout.write(dataObject.toByteArrayOutputStream().toByteArray());
The method writeTo()
will let you append the contents of a ByteArrayOutputStream
to any other OutputStream
.
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