Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i... LogonUser Function : impersonate a windows user // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES:  // This sample can be run only ...
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;
    }
}