73 lines
1.9 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// serialization/Blips.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Simple use of Externalizable & a pitfall.
import java.io.*;
class Blip1 implements Externalizable {
public Blip1() {
2015-11-03 12:00:44 -08:00
System.out.println("Blip1 Constructor");
2015-06-15 17:47:35 -07:00
}
@Override
public void writeExternal(ObjectOutput out)
throws IOException {
2015-11-03 12:00:44 -08:00
System.out.println("Blip1.writeExternal");
2015-06-15 17:47:35 -07:00
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
2015-11-03 12:00:44 -08:00
System.out.println("Blip1.readExternal");
2015-06-15 17:47:35 -07:00
}
}
class Blip2 implements Externalizable {
Blip2() {
2015-11-03 12:00:44 -08:00
System.out.println("Blip2 Constructor");
2015-06-15 17:47:35 -07:00
}
@Override
public void writeExternal(ObjectOutput out)
throws IOException {
2015-11-03 12:00:44 -08:00
System.out.println("Blip2.writeExternal");
2015-06-15 17:47:35 -07:00
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
2015-11-03 12:00:44 -08:00
System.out.println("Blip2.readExternal");
2015-06-15 17:47:35 -07:00
}
}
public class Blips {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
2015-11-03 12:00:44 -08:00
System.out.println("Constructing objects:");
2015-06-15 17:47:35 -07:00
Blip1 b1 = new Blip1();
Blip2 b2 = new Blip2();
try(ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blips.out"))) {
2015-11-03 12:00:44 -08:00
System.out.println("Saving objects:");
2015-06-15 17:47:35 -07:00
o.writeObject(b1);
o.writeObject(b2);
}
// Now get them back:
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.out"));
2015-11-03 12:00:44 -08:00
System.out.println("Recovering b1:");
2015-06-15 17:47:35 -07:00
b1 = (Blip1)in.readObject();
// OOPS! Throws an exception:
2015-11-03 12:00:44 -08:00
//! System.out.println("Recovering b2:");
2015-06-15 17:47:35 -07:00
//! b2 = (Blip2)in.readObject();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Constructing objects:
Blip1 Constructor
Blip2 Constructor
Saving objects:
Blip1.writeExternal
Blip2.writeExternal
Recovering b1:
Blip1 Constructor
Blip1.readExternal
2015-09-07 11:44:36 -06:00
*/