Concatenate ByteArrayOutputStream

Vincent picture Vincent · Jan 19, 2011 · Viewed 9.5k times · Source
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;
        }
    } 

Answer

Peter Lawrey picture Peter Lawrey · Jan 19, 2011

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());