2014-01-13 61 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 
    } 
} 
相關問題