Java DExternalizable.writeExternal(ObjectOutput out)方法範例

2019-10-16 22:17:01

Java Externalizable.readExternal(ObjectInput in)方法範例

Externalizable.readExternal(ObjectInput in)方法的語法如下。

void readExternal(ObjectInput in)   throws IOException ,    ClassNotFoundException

範例

在下面的程式碼中展示了如何使用Externalizable.readExternal(ObjectInput in)方法。

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

class A implements Externalizable {
    public A() {
        System.out.println("A Constructor");
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("A.writeExternal");
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        System.out.println("A.readExternal");
    }
}

class B implements Externalizable {
    B() {
        System.out.println("B Constructor");
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("B.writeExternal");
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        System.out.println("B.readExternal");
    }
}

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        A b1 = new A();
        B b2 = new B();
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("File.out"));
        o.writeObject(b1);
        o.writeObject(b2);
        o.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("File.out"));
        b1 = (A) in.readObject();
    }
}

上面的程式碼生成以下結果。

A Constructor
B Constructor
A.writeExternal
B.writeExternal
A Constructor
A.readExternal