Java Externalizable .writeExternal (ObjectOutput out)
Syntax
Externalizable.writeExternal(ObjectOutput out) has the following syntax.
void writeExternal(ObjectOutput out) throws IOException
Example
In the following code shows how to use Externalizable.writeExternal(ObjectOutput out) method.
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;
/*from w ww . java 2 s. c o m*/
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();
}
}
The code above generates the following result.
Home »
Java Tutorial »
java.io »
Java Tutorial »
java.io »