2014-01-13 21 views
1

如何将多个元素放入byte[]?我有以下3个元素:1)String data,2)String status和3)HashMap<String,String> headers,它们需要作为字节数组传递给setContent(byte[] data)。下面是我想用以前的3个参数作为输入statusResult.setContent()代码:如何将多个元素放入java的byte []中

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[]); 
} 

有人可以帮我解决了这一点?

+0

什么,你希望把'data'元素呢?目前还不清楚.. – Maroun

+0

@ᴍarounᴍaroun我把从响应收到的字符串消息放入数据中,它将作为“hello world”的小行。 –

+0

您需要在将对象放入字节[]之前序列化对象。您是否真的知道在将这些字节作为序列化数据传递给该对象之后会发生什么?该对象是否会以适当的方式解释它们? – Ricardo

回答

1

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

  1. 创建封装三个元素的类。
  2. 确保类implementsserializable接口。
  3. 使用下面的代码[从this post]采取创建一个字节数组,你想,从字节数组读取对象回(它,尽管你还没有指定的要求,但需要提到的完整性)的缘故
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 
    } 
} 
相关问题