byte数组与对象之间的相互转换

在进行网络通信时可能需要传输对象,如果用NIO的话,只能用Bytebuffer和channel直接

通过ByteArray*Stream和Object*Stream可以将byte数组和对象进行相互的转换。

1.byte数组转对象:

byte [] data=initData();//初始化byte数组

ByteArrayInputStream inputStream=new ByteArrayInputStream(data);

ObjectInputStream oInputStream=new ObjectInputStream(inputStream);

Object obj=oInputStream.readObject();

2.将对象转化成byte数组

Object myObj=new Object();

ByteArrayOutputStream outputStream=new ByteArrayOutputStream();

ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);

objectOutputStream.writeObject(myObj);

byte[] data=outputStream.toByteArray();

 

你可能感兴趣的:(byte)