Java Reference
In-Depth Information
Try It Out - Writing Objects to a File
We will first define a serializable class that has some arbitrary fields with different data types:
import java.io.Serializable;
public class Junk implements Serializable {
private static java.util.Random generator = new java.util.Random();
private int answer; // The answer
private double[] numbers; // Valuable data
private String thought; // A unique thought
public Junk(String thought) {
this.thought = thought;
answer = 42; // Answer always 42
numbers = new double[3+generator.nextInt(4)]; // Array size 3 to 6
for(int i = 0 ; i<numbers.length ; i++) // Populate with
numbers[i] = generator.nextDouble(); // random values
}
public String toString() {
StringBuffer strBuf = new StringBuffer(thought);
strBuf.append('\n').append(String.valueOf(answer));
for(int i = 0 ; i<numbers.length ; i++)
strBuf.append("\nnumbers[")
.append(String.valueOf(i))
.append("] = ")
.append(numbers[i]);
return strBuf.toString();
}
}
An object of type
Junk
has three instance fields, a simple integer that is always 42, a
String
object,
and an array of
double
values. The
toString()
method provides a
String
representation of a
Junk
object that we can output to the command line. The static field,
generator
, will not be written
to the stream when an object of type
Junk
is serialized. The only provision we have made for
serializing objects of type
Junk
is to declare that the class implements the
Serializable
interface.
We can write objects of this class type to a file with the following program:
import java.io.*;
public class SerializeObjects {
public static void main(String[] args) {
Junk obj1 = new Junk("A green twig is easily bent.");
Junk obj2 = new Junk("A little knowledge is a dangerous thing.");
Junk obj3 = new Junk("Flies light on lean horses.");
ObjectOutputStream objectOut = null;