Java Reference
In-Depth Information
an ObjectInputStream areusedinsteadof FileOutputStream and ObjectOutputStream .
Objects should be read from the file in the order in which they are written. The readObject
method can be used to read an object from the file.
Note that there are also methods for working with primitive types, such as
writeDouble / readDouble , writeBoolean / readBoolean , and so on. For example, the
writeChars method can be used to store a String in the binary file.
Below is the code for the Person class. Note that the class implements the interface
Serializable . This means that an object that belongs to the Person class can be saved
(or serialized) on the hard disk.
public class Person implements Serializable
{
private long id ;
private String name;
private static long idCounter = 0;
private Address address ;
private long phoneNumber ;
public Person(String name, Address address , long phoneNumber)
{
id = idCounter ;
idCounter++;
this .name = name;
this . phoneNumber = phoneNumber ;
this . address = address ;
}
public String toString() {
return "name = " +name+ "" + address + " Phone number: " +
phoneNumber ;
}
public long getID()
{
return id ;
}
public static class Address implements Serializable
{
private int streetNumber ;
private String streetName;
private String cityName;
private String state ;
private int zipCode ;
public Address( int streetNumber , String streetName , String cityName
, String state , int zipCode) {
this . streetNumber = streetNumber ;
this . streetName = streetName ;
this . cityName = cityName ;
this . state = state ;
this . zipCode = zipCode ;
}
public String toString() {
return "Address: " + streetNumber + "" + streetName + "" +
cityName + "" +zipCode+ "" + state ;
}
}
 
Search WWH ::




Custom Search