如何在java中将多个元素放入byte []

时间:2014-01-13 06:34:21

标签: java http http-headers bytearray

如何将多个元素放入byte[]?我有以下3个元素:1)String data,2)String status和3)HashMap<String,String> headers,需要作为字节数组传递给setContent(byte[] data)。以下是我想使用前面3个参数作为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[]);
}

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这是粗略的序列化。我建议如下:

  1. 创建封装三个元素的类
  2. 确保课程implements serializable界面。
  3. 根据需要使用以下代码[取自 this post] 创建字节数组,并从字节数组中读取对象(虽然你没有指明要求,但为了完整性需要提及
  4. 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
      }
    }