JAVA序列化

来源:互联网 发布:帝国cms采集插件下载 编辑:程序博客网 时间:2024/06/05 18:59
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;/** * @2017年9月1日@上午10:07:48 * @Endless * @ArraySerialize.java * @version集合序列化和反序列化 */public class ArraySerialize {    private static ArrayList<Object> DeSerialize() throws IOException, ClassNotFoundException {        // 反序列化        ArrayList<Object> arr = new ArrayList<Object>();        ObjectInputStream oo = new ObjectInputStream(new FileInputStream("D:/1.txt"));        for (int i = 0; i < 20; i++) {            tv x1 = (tv) oo.readObject();            arr.add(x1);        }        oo.close();        return arr;    }    public static void main(String[] args) throws IOException, ClassNotFoundException {        ArrayList<Object> arr = new ArrayList<Object>();        for (int i = 0; i < 20; i++) {            arr.add(new tv(i));        }        Serialize(arr);        ArrayList<Object> arrs = DeSerialize();        arrs.forEach(x -> ((tv) x).show());        for (int i = 0; i < 20; i++) {            arrs.get(5);        }    }    @SuppressWarnings("rawtypes")    private static void Serialize(ArrayList x) throws IOException {        // 序列化        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("D:/1.txt"));        for (int i = 0; i < x.size(); i++) {            oo.writeObject(x.get(i));        }        oo.close();    }}class tv implements Serializable {    private static final long serialVersionUID = 1L;    int x;    tv(int x) {        System.out.println(x + "序列化此对象");        this.x = x;    }    public void show() {        System.out.println(x + "序列化及反成功!");    }}
原创粉丝点击