Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... DNS SERVER LIST Google 8.8.8.8 8.8.4.4 TWNIC 192.83.166.11 211.72.210.250 HiNet 168.95.1.1 168.95.192.1 Seednet 北區 DNS (台北, 桃園, 新竹, 宜蘭, 花蓮, 苗栗) 139.... CORS in Asp.net MVC Web API v2 Step 1. Install cors from NeGet Step 2. Enable cors in config using System; using System.Collections.Generic; using System.Linq; using ...
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;
    }
}