Question

How can I put multiple elements into byte[]? I have the following 3 elements: 1) String data , 2) String status and 3) HashMap<String,String> headers, which need to be passed to setContent(byte[] data) as byte arrays. The following is the code in which I would like to use the previous 3 parameters as input for statusResult.setContent():

public void onSuccess(ClientResponse clientResponse){
      String data=clientResponse.getMessage();
      String status=String.valueOf(clientResponse.getStatus());
      HashMap<String,String> headers=clientResponse.getHeaders();

    // Now StatusResult is a class where we need to pass all this data,having only getters and
   //  setters for Content,so here in the next line i need to pass data,status and headers as 
  //   a byte[] to setContent.

       statusResult.setContent(byte[]);
}

Can somebody help me to resolve this out?

Was it helpful?

Solution

This is serialization in a crude way. I would suggest the following:

  1. Create a class encapsulating the three elements.
  2. Make sure that class implements serializable interface.
  3. Use the following code [taken from this post] to create a byte array as you wished, and read the object back from byte array (which, although you have not specified as requirement, but it needs mention for the sake of completeness)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  //Assuming that bos is the object to be seriaized
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  try {
    if (out != null) {
      out.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}
//Create object from bytes:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} finally {
  try {
    bis.close();
  } catch (IOException ex) {
    // ignore close exception
  }
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top