JAVA序列化


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 DeSerialize() throws IOException, ClassNotFoundException {
        // 反序列化
        ArrayList arr = new ArrayList();
        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 arr = new ArrayList();
        for (int i = 0; i < 20; i++) {
            arr.add(new tv(i));
        }
        Serialize(arr);
        ArrayList 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 + "序列化及反成功!");
    }
}
 
  

                            
                        
                    
                    
                    

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