将Object转为byte可以获取长度,在传输过程方便制定协议
</pre><pre name="code" class="java">import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Object2Byte {
public static byte[] toByte(Object obj){
try {
ObjectOutputStream os = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
os.flush();
os.writeObject(obj);
os.flush();
byte[] result = byteStream.toByteArray();
os.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}