当前位置: 代码迷 >> J2SE >> java类对象转化为byte数组,该怎么解决
  详细解决方案

java类对象转化为byte数组,该怎么解决

热度:85   发布时间:2016-04-24 02:31:30.0
java类对象转化为byte数组
本人有一个类
public class packhead implements Serializable
{
  byte[] from = new byte[16];
  byte[] to = new byte[16];
  int ntype;
  int nlength;
}
在socket通讯的时候这么写,但是效果却达不到,
packhead headheart = new packhead();
  String strHeadFrom = "javaserver";
  headheart.from = strHeadFrom.getBytes();
  strHeadFrom = "vcclient";
  headheart.to = strHeadFrom.getBytes();
  headheart.nlength = 40;
  headheart.ntype = 90;
   
   
   
  Byte_File_Object objto= new Byte_File_Object();
  byte[] bufobject1 = objto.getBytesFromObject(headheart);
   
  System.out.print("\n转换后的数据为" + bufobject1);
   
  packhead headto = (packhead) objto.getObjectFromBytes(bufobject1);
   
  byte[] bufobject2 = objto.getBytesFromObject(headto);
  System.out.print("\n反转回来" + bufobject2);
其中使用的转化类
class Byte_File_Object {

  public static Object getObjectFromBytes(byte[] objBytes) throws Exception {
  if (objBytes == null || objBytes.length == 0) {
  return null;
  }
  ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
  ObjectInputStream oi = new ObjectInputStream(bi);
  return oi.readObject();
  }

  public static byte[] getBytesFromObject(Serializable obj) throws Exception {
  if (obj == null) {
  return null;
  }
  ByteArrayOutputStream bo = new ByteArrayOutputStream();
  ObjectOutputStream oo = new ObjectOutputStream(bo);
  oo.writeObject(obj);
  return bo.toByteArray();
  }

}
转化后的数据发送到客户端是乱码,而且转换前后数据都不对应了。


------解决方案--------------------
新旧Byte对象的hashcode不一样
------解决方案--------------------
楼主其实不用这么麻烦。直接用ObjectOutputStream 和ObjectInputStream的readObject和writeObject方法即可。很方便
代码如下:
Client:
Java code
import java.io.ObjectOutputStream;import java.io.OutputStream;import java.io.Serializable;import java.net.Socket;public class Client {    public static void main(String[] args) throws Exception {        Socket s = new Socket("localhost", 8189);        OutputStream out = s.getOutputStream();        ObjectOutputStream objectout = new ObjectOutputStream(out);        packhead headheart = new packhead();        String strHeadFrom = "javaserver";        headheart.from = strHeadFrom.getBytes();        strHeadFrom = "vcclient";        headheart.to = strHeadFrom.getBytes();        headheart.nlength = 40;        headheart.ntype = 90;        objectout.writeObject(headheart);        System.out.println("发送完毕");         Thread.sleep(5000);        s.close();    }}class packhead implements Serializable {    byte[] from = new byte[16];    byte[] to = new byte[16];    int ntype;    int nlength;}
  相关解决方案