Popular Posts
Word break tag : <wbr/> (HTML5) The  HTML  <wbr>  tag  is  used  defines  a  potential  line  break  point  if  needed.  This  stands  for  Word  BReak. This  is  u... CTE, recursive search WITH DepartmentSearch(DeptID, DeptParent, DeptName, OuID) AS (     -- 找出簽核者所屬部門     SELECT d.DeptID, d.DeptParent, d.DeptName, d.OuID     FR... Create web service client cross SSL with eclipse When creating web service cross SSL using eclipse, it occuss some error like below: And it can't build the client source from this wa...
Blog Archive
Stats
Object serialize/ deserialize
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TransientMember {

    /**
     * @param args
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // create new user with account & password
        User user = new User();
        user.account = "bruce";
        user.password = "mypassword";
        System.out.println(user);
        // serialize
        byte[] buffer = user.serialize();

        // deserialize from byte array
        User user2 = User.deserialize(buffer);
        System.out.println(user2);
    }

}

class User implements Serializable {
    public String account;
    transient public String password;  // would not be serialize

    @Override
    public String toString() {
        return String.format("<user account:%s password:%s>", this.account, this.password);
    }

    public byte[] serialize() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);
        oos.close();
        baos.close();
        return baos.toByteArray();
    }

    public static User deserialize(byte[] buf) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object o = ois.readObject();
        ois.close();
        bais.close();
        return (User) o;
    }
}