Java ObjectInputStream read Externalizable object from file
import java.io.Externalizable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; public class Main { public static void main(String[] args) { // Create three Person objects Code a = new Code("HTML", "Tag", 6.7); Code b = new Code("Java", "Object", 5.7); Code c = new Code("C", "function", 5.4); // The output file File fileObject = new File("code.ser"); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( fileObject))) {//w w w.j a va 2 s .c o m // Write (or serialize) the objects to the object output stream oos.writeObject(a); oos.writeObject(b); oos.writeObject(c); // Display the serialized objects on the standard output System.out.println(a); System.out.println(b); System.out.println(c); // Print the output path System.out.println("Objects were written to " + fileObject.getAbsolutePath()); } catch (IOException e1) { e1.printStackTrace(); } try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream( fileObject))) { // Read (or deserialize) the three objects a = (Code) ois.readObject(); b = (Code) ois.readObject(); c = (Code) ois.readObject(); // Let's display the objects that are read System.out.println(a); System.out.println(b); System.out.println(c); // Print the input path System.out.println("Objects were read from " + fileObject.getAbsolutePath()); } catch (FileNotFoundException e) { System.out.println(fileObject.getPath()); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } } } class Code implements Externalizable { private String name = "Unknown"; private String part = "Unknown"; private double height = Double.NaN; public Code() { } public Code(String name, String p, double height) { this.name = name; this.part = p; this.height = height; } public String toString() { return "Name: " + this.name + ", Part: " + this.part + ", Height: " + this.height; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.name = in.readUTF(); this.part = in.readUTF(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(this.name); out.writeUTF(this.part); } }