Object To array, array to object
Serialize an object. deserializing an object is like this.
Java code
Package com. digican. utils;
Import java. io. ByteArrayInputStream;
Import java. io. ByteArrayOutputStream;
Import java. io. IOException;
Import java. io. ObjectInputStream;
Import java. io. ObjectOutputStream;
Import com. digican. javabean. TestBean;
Public class ObjectAndByte {
/**
* Convert objects to Arrays
* @ Param obj
* @ Return
*/
Public byte [] toByteArray (Object obj ){
Byte [] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
Try {
ObjectOutputStream oos = new ObjectOutputStream (bos );
Oos. writeObject (obj );
Oos. flush ();
Bytes = bos. toByteArray ();
Oos. close ();
Bos. close ();
} Catch (IOException ex ){
Ex. printStackTrace ();
}
Return bytes;
}
/**
* Array to object
* @ Param bytes
* @ Return
*/
Public Object toObject (byte [] bytes ){
Object obj = null;
Try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes );
ObjectInputStream ois = new ObjectInputStream (bis );
Obj = ois. readObject ();
Ois. close ();
Bis. close ();
} Catch (IOException ex ){
Ex. printStackTrace ();
} Catch (ClassNotFoundException ex ){
Ex. printStackTrace ();
}
Return obj;
}
Public static void main (String [] args ){
TestBean tb = new TestBean ();
Tb. setName ("daqing ");
Tb. setValue ("1234567890 ");
ObjectAndByte oa = new ObjectAndByte ();
Byte [] B = oa. toByteArray (tb );
System. out. println (new String (B ));
System. out. println ("========================================== = ");
TestBean teb = (TestBean) oa. toObject (B );
System. out. println (teb. getName ());
System. out. println (teb. getValue ());
}
}
package com.digican.javabean;
import java.io.Serializable;
public class TestBean implements Serializable{
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}