如何将多个元素放入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[]);
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
这是粗略的序列化。我建议如下:
implements
serializable
界面。 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 } }