java序列化反序列化ArrayList集合

    /**
     * 生成序列化
     * 
     * @throws IOException
     */
    public void serialization() throws IOException {
        File File = new File("D:\\File\\ut");
        OutputStream os = new FileOutputStream(File);
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(list);
        oos.close();
        os.close();
    }

    /**
     * 反序列化
     * 
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public void Inserialization() throws IOException, ClassNotFoundException {
        File File = new File("D:\\File\\ut");
        InputStream is = new FileInputStream(File);
        ObjectInputStream ois = new ObjectInputStream(is);
        List tList = (List) ois.readObject();
        System.out.println(tList.size());
        for (Students s : tList) {
            System.out.println(s.getNum() + s.getName() + s.getAge()
                    + s.getGenber() + T.format(s.getTime())
                    + T.format(s.getXtime()));
        }
        ois.close();
        is.close();
    }

Students类必须implements Serializable,才能序列化;

package Administrate;

import java.io.Serializable;
import java.util.Date;

import org.ietf.jgss.Oid;

public class Students implements Serializable{
    private int Num;//学生编号
    private String Name;//学生姓名
    private Byte Age;//学生年龄
    private String Genber;//学生性别
    private Date Time;//创建时间
    private Date Xtime; //修改时间
    public Students(int Num,String Name,Byte Age,String Genber,Date Time,Date Xtime){
        this.Num=Num;
        this.Name=Name;
        this.Age=Age;
        this.Genber=Genber;
        this.Time=Time;
        this.Xtime=Xtime;
    }
    public Students(String Name,Byte Age,String Genber){
        this.Name=Name;
        this.Age=Age;
        this.Genber=Genber;
    }
    public Students(){

    }
    /**
     * 封装
     */
    public int getNum() {
        return Num;
    }
    public void setNum(int num) {
        Num = num;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public Byte getAge() {
        return Age;
    }
    public void setAge(Byte age) {
        Age = age;
    }
    public String getGenber() {
        return Genber;
    }
    public void setGenber(String genber) {
        Genber = genber;
    }
    public Date getTime() {
        return Time;
    }
    public void setTime(Date time) {
        Time = time;
    }
    public Date getXtime() {
        return Xtime;
    }
    public void setXtime(Date xtime) {
        Xtime = xtime;
    }
    public void xiugai(){
        this.Xtime=new Date();
    }
}

你可能感兴趣的:(Java序列化)