1.首先对象要继承Serializable接口
将字节转换为对象
- public static Object ByteToObject(byte[] bytes) {
- Object obj = null;
- try {
- // bytearray to object
- ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
- ObjectInputStream oi = new ObjectInputStream(bi);
- obj = oi.readObject();
- bi.close();
- oi.close();
- } catch (Exception e) {
- System.out.println("translation" + e.getMessage());
- e.printStackTrace();
- }
- return obj;
- }
将对像转换为字节
- public static byte[] ObjectToByte(java.lang.Object obj) {
- byte[] bytes = null;
- try {
- // object to bytearray
- ByteArrayOutputStream bo = new ByteArrayOutputStream();
- ObjectOutputStream oo = new ObjectOutputStream(bo);
- oo.writeObject(obj);
- bytes = bo.toByteArray();
- bo.close();
- oo.close();
- } catch (Exception e) {
- System.out.println("translation" + e.getMessage());
- e.printStackTrace();
- }
- return bytes;
- }
本文介绍如何在Java中实现对象与字节之间的相互转换,包括将对象序列化为字节数组以便于在网络中传输或存储,以及将字节数组反序列化为原始对象的过程。
1329

被折叠的 条评论
为什么被折叠?



