RandomTest2.java
Select all
/* RandomTest2.java CIS 260 David Klick 2006-01-25 This program demonstrates random access file techniques. This is a modification of RandomTest.java to avoid writing out Unicode characters. This code converts the Strings to bytes before writing them to the file and converts the bytes back to a String as it reads them in. */ import java.io.*; class Student { public static final int SIZE = 52; 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.writeBytes(convert(firstName, 20)); rf.writeBytes(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 { byte[] buf = new byte[n]; rf.read(buf); return new String(buf).trim(); } } public class RandomTest2 { private static RandomAccessFile rfile; public static void main(String[] args) { // create and write file openRandomFile("student.ra"); addStudents(); // read and display file displayStudents(); closeRandomFile(); } private static void openRandomFile(String filename) { try { rfile = new RandomAccessFile(filename, "rw"); } 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