import Chapter2.MyInput; import java.io.*; public class Raf { public static void main(String[] args) { Person p = new Person(); // make an empty person RandomAccessFile file=null; try { file = new RandomAccessFile("person.dat", "rw"); // no append! } catch (Exception e) { System.out.println(e); } String choice=null; do { System.out.println("Enter data for a person:"); p.getPerson(); p.writePerson(file); System.out.print("Do more? (y/n): "); choice = MyInput.readString(); } while(choice.equals("y")); try { System.out.println("File Size " + file.length()); } catch (Exception e) { System.out.println(e); } int pnum; do { System.out.print("Enter a person number:"); pnum = MyInput.readInt(); p.readPerson(file, pnum); p.showPerson(); System.out.print("Do more? (y/n): "); choice = MyInput.readString(); } while(choice.equals("y")); } } class Person { private int id; private char grade; public void getPerson() { System.out.print("Enter id: "); id = MyInput.readInt(); System.out.print("Enter grade: "); grade = MyInput.read1char(); } public void writePerson(RandomAccessFile raf) { try { raf.writeInt(id); raf.writeChar(grade); } catch (Exception e) { System.out.println(e); } } public void readPerson(RandomAccessFile raf, int pid) { long pos = pid * (4+2); // 1char = 2bytes try { raf.seek(pos); id = raf.readInt(); grade = raf.readChar(); } catch (Exception e) { System.out.println(e); } } public void showPerson() { System.out.println("Id: " + id); System.out.println("Grade: " + grade); } }