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<Students> tList = (List<Students>) 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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章