//== Create a RandomAccessFile == // Creates a RandomAccessFile with names and salaries (money) // The program allocates 50 bytes for each recored - // 40 bytes for the name field // 10 bytes for the salary field // The commands .writeUTF and .readUTF use the following system: // First a two bytes tell the length of the following string, // and the following bytes contain the string (1 char per byte) // The double value occupies 8 bytes. // So there are 42 bytes for the name = 2 bytes for length, 40 bytes for data. // If shorter strings are recorded, the extra bytes are empty (wasted). //============================================================================= import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; public class RanFile extends EasyApp // EasyApp contains IBIO // + standard constructor stuff { public static void main(String[] args) { new RanFile(); } // Instantiate object = start program Button bWrite = addButton("Write Record",30,30,100,50,this); Button bRead = addButton("Read Record",130,30,100,50,this); public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == bWrite) { writeRecord();} if (source == bRead) { readRecord(); } } public void writeRecord() { try { RandomAccessFile file = new RandomAccessFile("salaries.dat","rw"); long pos = inputLong("Type the record number for saving the data:"); String name = input("Type the employees's name:"); if (name.length() > 40) { name = name.substring(0,40);} double salary = inputDouble("Type the employee's salary:"); file.seek(50*pos); file.writeUTF(name); file.seek(50*pos + 42); file.writeDouble(salary); } catch (IOException e) { output(e.toString());} } public void readRecord() { try { RandomAccessFile file = new RandomAccessFile("salaries.dat","r"); long pos = inputLong("Type the record number for reading the data:"); file.seek(50*pos); String name = file.readUTF(); file.seek(50*pos + 42); double salary = file.readDouble(); output("Record #" + pos + " = " + name + " : " + salary); } catch (IOException e) { output(e.toString());} } } |