Java从文件

时间:2018-10-31 12:42:53

标签: serialization deserialization

我有一个作业来分别序列化和反序列化多个Demo_2 []对象。

序列化正在工作,但是我不知道如何反序列化(在//对象反序列化的方法下),我得到了异常-IOException被捕获到java.io.OptionalDataException。

有人可以为此提供正确的方法吗?

我的代码:

class Demo_2 implements java.io.Serializable {
private static int s1;
private final int a;
private final String b;
private final transient int c;

static {
    s1 = 1;
}
public Demo_2(int a, String b, int c){
    this.a = a;
    this.b = b;
    this.c = c;
}
public int getA() {
    return a;
}

public String getB() {
    return b;
}

public static int getS() {
    return s1;
}

public static void setS(int s) {
    Demo_2.s1 = s;
}

public int getC() {
    return c;
}

@Override
public String toString() {
    return "Demo_2[]{" + "a=" + a + ", b=" + b + ", c=" + c + '}' + " s=" + s1;
}
}


public class Serialization {

public static void main(String[] args) {
    Demo_2[] objects = {new Demo_2(1, "demo 1", 2),
                        new Demo_2(2, "demo 1", 4),
                        new Demo_2(3, "demo 1", 6)};
    String filename = "file.ser";

    // Serialization 
    try {
        //Saving of object in a file
        FileOutputStream file = new FileOutputStream(filename);
        ObjectOutputStream out = new ObjectOutputStream(file);

        // Method for serialization of object
        out.writeInt(objects.length);
        for (Object obj : objects) {
            out.writeObject(obj);
        }
        out.close();
        file.close();

        System.out.println("Object has been serialized");
        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[i]);
        }

    } catch (IOException ex) {
        System.out.println("IOException is caught");
    }

    Demo_2[] objects1 = null;
    Demo_2.setS(0);

    System.out.println("");

    // Deserialization
    try {

        // Reading the object from a file
        FileInputStream file = new FileInputStream(filename);
        ObjectInputStream in = new ObjectInputStream(file);

        // Method for deserialization of object

        System.out.println("Object has been deserialized ");
        while ((objects1 = (Demo_2[]) in.readObject()) != null){
            System.out.println("" + objects1);
        }
        in.close();
        file.close();

    } catch (IOException ex) {
        System.out.println("IOException is caught" + ex);
    } catch (ClassNotFoundException ex) {
        System.out.println("ClassNotFoundException is caught" + ex);
    }

}
}

0 个答案:

没有答案