Java provides a very simple, and relatively limited, means to store your data model in a file. This can be done by simply implementing the Serializable
interface.
public class Person implements Serializable {
private final String firstName, initials, lastName;
// ...
}
This simple addition to your class definition allows it to be saved to an ObjectOutputStream
.
One important point: All member variables and their types must now also be Serializable
for this to work.
To have some data to save we use the following model as an example. It is basically the same structure used in several OoP example.
As show above, the Person
implements the Serializable
interface. (Step 1)
Since all member variables are basic Java types (String and int) this class can be exported using this single change to the original model.
You model can now be written to a file using an ObjectOutputStream
.
// Create some data.
Student s = new Student("Mark", "M.", "Hamill", 12345);
Teacher t = new Teacher("Frederik", "F.", "Bonte", "fbo11", "ing.");
// Create an Object Output Stream.
String filename = "resources/objects.obj";
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// Write some data...
oos.writeObject(t);
oos.writeObject(s);
// Close the stream (and the containing file).
oos.close();
Now the “objects.obj” file contains some binary data. You may wish to explore its content. But the basic idea is that both objects are now stored in this file.
This file was generated with this version of your code. Any changes to any of the stored classes, like Adding an new optional field for instance, will prevent you from reading this file.
You can only read files created using this version of the objects. Any change to any object will break this file.
This file is stored in a binary format and is not meant to be edited.
Objects are stored in a particular order. Reading the file demands that very same order.
Since an ObjectOutputStream
wrote this data, it seems logical than an ObjectInputStream
can be used to read it.
// Create an Object Input Stream.
String filename = "resources/objects.obj";
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
// Read objects in the SAME order.
Teacher other_t = (Teacher)ois.readObject();
Student other_s = (Student)ois.readObject();
// Close the stream (and the containing file).
ois.close();
// Show that reading succeeded.
System.out.println(other_s);
System.out.println(other_t);
Stuff to try out:
ArrayList
of Person
s?Student
s and Teacher
s to that list?Teacher
stores a list of Student
s?