Java可序列化對象到ByteArray假設我有一個可序列化的類AppMessage.我想把它作為byte[]從套接字到另一臺機器,從接收到的字節重建它。我怎樣才能做到這一點?
3 回答
Qyouu
TA貢獻1786條經驗 獲得超11個贊
ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutput out = null;try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
...} finally {
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}}ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);ObjectInput in = null;try {
in = new ObjectInputStream(bis);
Object o = in.readObject();
...} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}}添加回答
舉報
0/150
提交
取消
