下面是一个应该反序列化员工记录的程序。它会反序列化第一条记录,但不会反序列化用户添加的其他记录。
import java.io.*;
import java.util.*;
public class Employee implements Serializable {
private Object name;
private Object address;
private Object ssn;
private Object eadd;
private Object number;
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
}
private void readObject (ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
}
public static void addEmployee() {
try {
Employee e = new Employee();
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fileOut = new FileOutputStream("employee.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println("Name: ");
e.name = buffer.readLine();
System.out.println("Address: ");
e.address = buffer.readLine();
System.out.println("SSN: ");
e.ssn = buffer.readLine();
System.out.println("Email: ");
e.eadd = buffer.readLine();
System.out.println("Number: ");
e.number = buffer.readLine();
out.writeObject(e +"#");
out.close();
fileOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void deserializeAll() throws ClassNotFoundException {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.ssn);
System.out.println("Email: " + e.eadd);
System.out.println("Number: " + e.number);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
int choice;
Scanner input = new Scanner (System.in);
do {
System.out.println("[1] Add an employee.");
System.out.println("[2] Deserialize all.");
choice = input.nextInt();
switch (choice) {
case 1: addEmployee(); break;
case 2: deserializeAll(); break;
default: System.exit(0);
}
} while (choice != 3);
}
}
#
是每条记录的分隔符。