Java知识积累:序列化、反序列化

阅读更多

http://fangguanhong.iteye.com/blog/1976911

 

import java.io.Serializable;

class Customer implements Serializable {
    private static final long serialVersionUID = 1324123542315L;
    private String name;
    private int age;
    private String address;
    private String address1;

    public Customer(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public String toString() {
        return "name=" + name + ", age=" + age + ", address=" + address;
    }
}

 

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;

/**
 * @see反序列化测试类。 Created with IntelliJ IDEA. User: Administrator Date: 13-12-11
 *              Time: 下午5:16 To change this template use File | Settings | File
 *              Templates.
 */
public class ObjectClient {
    public static void main(String[] args) {
        // 反序列化对象
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(".\\objectFile.obj"));
            System.out.println("obj1=" + (String) in.readObject());
            System.out.println("obj2=" + (Date) in.readObject());
            Customer obj3 = (Customer) in.readObject();
            System.out.println("obj3=" + obj3);
            int obj4 = in.readInt();
            System.out.println("obj4=" + obj4);
            int obj5 = in.readInt();
            System.out.println("obj5=" + obj5);
            in.close();
        } catch (ClassNotFoundException enf) {
            System.out.println("ClassNotFound");
            enf.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * Created with IntelliJ IDEA. User: Administrator Date: 13-12-11 Time: 下午5:08
 * To change this template use File | Settings | File Templates.
 * 
 * @see对象的序列化 从输入流中读取数据的顺序(类型)要和写入流时候的顺序对应
 */
public class ObjectServer {
    private static String hello = "你好";
    private static int number = 1234;

    public static void main(String[] args) throws Exception {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(".\\objectFile.obj"));
        // 序列化对象
        Customer customer = new Customer("阿蜜果", 24, "GuangZhouChina");
        out.writeObject(hello);
        out.writeObject(new Date());
        out.writeObject(customer);
        out.writeInt(number);
        out.writeInt(123); // 写入基本类型数据
        out.close();
    }
}

 

你可能感兴趣的:(java)