Java Reference
In-Depth Information
You need to serialize a class (save the contents of the class) so that you can restore it at
a later time.
Solution
Java implements a built-in serialization mechanism. You access that mechanism via the
ObjectOutputStream class. In the following example, the method saveSet-
tings() uses an ObjectOutputStream to serialize the settings object in prepar-
ation for writing the object to disk:
public class Ch_8_1_SerializeExample {
public static void main(String[] args) {
Ch_8_1_SerializeExample example = new
Ch_8_1_SerializeExample();
example.start();
}
private void start() {
ProgramSettings settings = new ProgramSettings(
new Point(10,10),
new
Dimension(300,200),
Color.blue,
"The title of the application" );
saveSettings(settings,"settings.bin");
ProgramSettings loadedSettings
= loadSettings("settings.bin");
System.out.println("Are settings are equal?
:"+loadedSettings.equals(settings));
}
private void saveSettings(ProgramSettings settings,
String filename) {
try {
FileOutputStream fos = new
Search WWH ::




Custom Search