81 lines
2.1 KiB
Java
Raw Permalink Normal View History

2015-11-03 12:00:44 -08:00
// serialization/Blips.java
// (c)2021 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Simple use of Externalizable & a pitfall
2015-06-15 17:47:35 -07:00
import java.io.*;
class Blip1 implements Externalizable {
2017-05-01 17:43:21 -06:00
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 {
2017-01-22 16:48:11 -08:00
public static void main(String[] args) {
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.serialized"))
) {
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);
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
// Now get them back:
2015-11-03 12:00:44 -08:00
System.out.println("Recovering b1:");
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.serialized"))
) {
2015-12-15 11:47:04 -08:00
b1 = (Blip1)in.readObject();
2017-01-22 16:48:11 -08:00
} catch(IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
2015-12-15 11:47:04 -08:00
}
2015-06-15 17:47:35 -07:00
// OOPS! Throws an exception:
2015-12-18 11:28:19 -08:00
//- System.out.println("Recovering b2:");
//- b2 = (Blip2)in.readObject();
2015-06-15 17:47:35 -07:00
}
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
*/