RandomTest.java
Select all
/* RandomTest.java CIS 260 David Klick 2006-01-25 This program demonstrates random access file techniques. */ import java.io.*; class Student { public static final int SIZE = 92; 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) { if (fname == null) fname = ""; if (fname.length() > 20) fname = fname.substring(0, 20); firstName = fname; } public void setLastName(String lname) { if (lname == null) lname = ""; if (lname.length() > 20) lname = lname.substring(0, 20); lastName = 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 void write(RandomAccessFile rf) throws IOException { rf.writeChars(convert(firstName, 20)); rf.writeChars(convert(lastName, 20)); rf.writeInt(id); rf.writeDouble(gpa); } private String convert(String s, int n) { StringBuffer sb; if (s == null) sb = new StringBuffer(n); else sb = new StringBuffer(s); sb.setLength(n); return sb.toString(); } public void read(RandomAccessFile rf) throws IOException { setFirstName(readString(rf, 20)); setLastName(readString(rf, 20)); setID(rf.readInt()); setGPA(rf.readDouble()); } private String readString(RandomAccessFile rf, int n) throws IOException { char[] buf = new char[n+1]; for (int i=0; i