SerialTest.java
Select all
/* SerialTest.java CIS 260 David Klick 2006-01-25 This program demonstrates how objects may be directly written to and read from a file by implementing the Serializable interface. */ import java.io.*; class Student implements Serializable { private String lastName; private String firstName; private int id; private double gpa; Student() { this("", "", 0, 0.0); } Student(String lname, String fname, int id, double gpa) { setFirstName(lname); setLastName(fname); setID(id); setGPA(gpa); } public void setFirstName(String fname) { firstName = (fname==null) ? "" : fname; } public void setLastName(String lname) { lastName = (lname==null) ? "" : lname; } public void setID(int id) { this.id = id; } public void setGPA(double gpa) { this.gpa = (gpa>=0) ? gpa : 0; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getID() { return id; } public double getGPA() { return gpa; } public String toString() { return id + ": " + lastName + ", " + firstName + " (" + gpa + ")"; } } public class SerialTest { private static ObjectOutputStream ofile; private static ObjectInputStream ifile; public static void main(String[] args) { // create and write file openOutputFile("student.ser"); addStudents(); closeOutputFile(); // read and display file openInputFile("student.ser"); displayStudents(); closeInputFile(); } private static void openOutputFile(String filename) { try { ofile = new ObjectOutputStream(new FileOutputStream(filename)); } catch (Exception e) { System.err.println("Error opening file."); System.exit(3); } } private static void addStudents() { Student[] st = new Student[5]; st[0] = new Student("Dave", "Klick", 16, 2.4); st[1] = new Student("Susan", "Shilling", 3254, 3.8); st[2] = new Student("Barb", "Burpee", 278, 2.9); st[3] = new Student("Ken", "Kettlebottom", 90, 3.4); st[4] = new Student("Tangwa", "Crangor", 421, 3.9); for (int i=0; i