Modify Record Number in a Random Access File

Hi Does anyone know if I can modify the record number in the random access file hardware.dat for each hardware record each time and update it in hardware.dat to display it? Also why does it say "Record does not exist" if I modify the record number for a hardware and try to update it but could not find that record?

Here is the code below:

-

// Exercise 14.11: HardwareRecord.java

package org.egan;// packaged for reuse

publicclass HardwareRecord

{

privateint recordNumber;

private String toolName;

privateint quantity;

privatedouble cost;

// no-argument constructor calls other constructor with default values

public HardwareRecord()

{

this(0,"",0,0.0);// call four-argument constructor

}// end no-argument HardwareRecord constructor

// initialize a record

public HardwareRecord(int number, String tool,int amount,double price)

{

setRecordNumber(number);

setToolName(tool);

setQuantity(amount);

setCost(price);

}// end four-argument HardwareRecord constructor

// set record number

publicvoid setRecordNumber(int number)

{

recordNumber = number;

}// end method setRecordNumber

// get record number

publicint getRecordNumber()

{

return recordNumber;

}// end method getRecordNumber

// set tool name

publicvoid setToolName(String tool)

{

toolName = tool;

}// end method setToolName

// get tool name

public String getToolName()

{

return toolName;

}// end method getToolName

// set quantity

publicvoid setQuantity(int amount)

{

quantity = amount;

}// end method setQuantity

// get quantity

publicint getQuantity()

{

return quantity;

}// end method getQuantity

// set cost

publicvoid setCost(double price)

{

cost = price;

}// end method setCost

// get cost

publicdouble getCost()

{

return cost;

}// end method getCost

}// end class HardwareRecord

-

// Exercise 14.11: RandomAccessHardwareRecord.java

// Subclass of HardwareRecord for random-access file programs.

package org.egan;// package for reuse

import java.io.RandomAccessFile;

import java.io.IOException;

publicclass RandomAccessHardwareRecordextends HardwareRecord

{

publicstaticfinalint SIZE = 46;

// no-argument constructor calls other constructor with default values

public RandomAccessHardwareRecord()

{

this(0,"",0,0.0);

}// end no-argument RandomAccessHardwareRecord constructor

// initialize a RandomAccessHardwareRecord

public RandomAccessHardwareRecord(int number, String tool,int amount,double price)

{

super(number,tool,amount,price);

}// end four-argument RandomAccessHardwareRecord constructor

// read a record from a specified RandomAccessFile

publicvoid read(RandomAccessFile file)throws IOException

{

setRecordNumber(file.readInt());

setToolName(readName(file));

setQuantity(file.readInt());

setCost(file.readDouble());

}// end method read

// ensure that name is proper length

private String readName(RandomAccessFile file)throws IOException

{

char name[] =newchar[15], temp;

for(int count = 0; count < name.length; count++)

{

temp = file.readChar();

name[count] = temp;

}// end for

returnnew String(name).replace('\0',' ');

}// end method readName

// write a record to specified RandomAccessFile

publicvoid write(RandomAccessFile file)throws IOException

{

file.writeInt(getRecordNumber());

writeName(file, getToolName());

file.writeInt(getQuantity());

file.writeDouble(getCost());

}// end method write

// write a name to file; maximum of 15 characters

privatevoid writeName(RandomAccessFile file, String name)throws IOException

{

StringBuffer buffer =null;

if (name !=null)

buffer =new StringBuffer(name);

else

buffer =new StringBuffer(15);

buffer.setLength(15);

file.writeChars(buffer.toString());

}// end method writeName

}// end RandomAccessHardwareRecord

-

// Exercise 14.11: CreateRandomFile.java

// creates random-access file by writing 100 empty records to disk.

import java.io.IOException;

import java.io.RandomAccessFile;

import org.egan.RandomAccessHardwareRecord;

publicclass CreateRandomFile

{

privatestaticfinalint NUMBER_RECORDS = 100;

// enable user to select file to open

publicvoid createFile()

{

RandomAccessFile file =null;

try// open file for reading and writing

{

file =new RandomAccessFile("hardware.dat","rw");

RandomAccessHardwareRecord blankRecord =new RandomAccessHardwareRecord();

// write 100 blank records

for (int count = 0; count < NUMBER_RECORDS; count++)

blankRecord.write(file);

// display message that file was created

System.out.println("Created file hardware.dat.");

System.exit(0);// terminate program

}// end try

catch (IOException ioException)

{

System.err.println("Error processing file.");

System.exit(1);

}// end catch

finally

{

try

{

if (file !=null)

file.close();// close file

}// end try

catch (IOException ioException)

{

System.err.println("Error closing file.");

System.exit(1);

}// end catch

}// end finally

}// end method createFile

}// end class CreateRandomFile

-

// Exercise 14.11: CreateRandomFileTest.java

// Testing class CreateRandomFile

publicclass CreateRandomFileTest

{

// main method begins program execution

publicstaticvoid main( String args[] )

{

CreateRandomFile application =new CreateRandomFile();

application.createFile();

}// end main

}// end class CreateRandomFileTest

-

// Exercise 14.11: MenuOption.java

// Defines an enum type for the hardware credit inquiry program's options.

publicenum MenuOption

{

// declare contents of enum type

PRINT(1),

UPDATE(2),

NEW(3),

DELETE(4),

END(5);

privatefinalint value;// current menu option

MenuOption(int valueOption)

{

value = valueOption;

}// end MenuOptions enum constructor

publicint getValue()

{

return value;

}// end method getValue

}// end enum MenuOption

-

// Exercise 14.11: FileEditor.java

// This class declares methods that manipulate hardware account records

// in a random access file.

import java.io.EOFException;

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.Scanner;

import org.egan.RandomAccessHardwareRecord;

publicclass FileEditor

{

RandomAccessFile file;// reference to the file

Scanner input =new Scanner(System.in);

// open the file

public FileEditor(String fileName)throws IOException

{

file =new RandomAccessFile(fileName,"rw");

}// end FileEditor constructor

// close the file

publicvoid closeFile()throws IOException

{

if (file !=null)

file.close();

}// end method closeFile

// get a record from the file

public RandomAccessHardwareRecord getRecord(int recordNumber)

throws IllegalArgumentException, NumberFormatException, IOException

{

RandomAccessHardwareRecord record =new RandomAccessHardwareRecord();

if (recordNumber < 1 || recordNumber > 100)

thrownew IllegalArgumentException("Out of range");

// seek appropriate record in a file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

record.read(file);

return record;

}// end method getRecord

// update record tool name in file

publicvoid updateRecordToolName(int recordNumber, String newToolName)

throws IllegalArgumentException, IOException

{

RandomAccessHardwareRecord record = getRecord(recordNumber);

if (record.getRecordNumber() == 0)

thrownew IllegalArgumentException("Record does not exist");

// seek appropriate record in file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

record.setToolName(newToolName);

record =new RandomAccessHardwareRecord(

record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());

record.write(file);// write updated record to file

}// end method updateRecordToolName

// update record in file

publicvoid updateRecordQuantity(int recordNumber,int newQuantity)

throws IllegalArgumentException, IOException

{

RandomAccessHardwareRecord record = getRecord(recordNumber);

if (record.getRecordNumber() == 0)

thrownew IllegalArgumentException("Record does not exist");

// seek appropriate record in file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

record.setQuantity(newQuantity);

record =new RandomAccessHardwareRecord(

record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());

record.write(file);// write updated record to file

}// end method updateRecordQuantity

// update record in file

publicvoid updateRecordCost(int recordNumber,double newCost)

throws IllegalArgumentException, IOException

{

RandomAccessHardwareRecord record = getRecord(recordNumber);

if (record.getRecordNumber() == 0)

thrownew IllegalArgumentException("Record does not exist");

// seek appropriate record in file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

record.setCost(newCost);

record =new RandomAccessHardwareRecord(

record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());

record.write(file);// write updated record to file

}// end method updateRecordCost

// add record to file

publicvoid newRecord(int recordNumber, String toolName,int quantity,double cost)

throws IllegalArgumentException, IOException

{

RandomAccessHardwareRecord record = getRecord(recordNumber);

if (record.getRecordNumber() != 0)

thrownew IllegalArgumentException("Record already exists");

// seek appropriate record in file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

record =new RandomAccessHardwareRecord(recordNumber, toolName, quantity, cost);

record.write(file);// write record to file

}// end method newRecord

// delete record from file

publicvoid deleteRecord(int recordNumber)throws IllegalArgumentException, IOException

{

RandomAccessHardwareRecord record = getRecord(recordNumber);

if (record.getRecordNumber() == 0)

thrownew IllegalArgumentException("Account does not exist");

// seek appropriate record in file

file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);

// create a blank record to write to the file

record =new RandomAccessHardwareRecord();

record.write(file);

}// end method deleteRecord

// read and display records

publicvoid readRecords()

{

RandomAccessHardwareRecord record =new RandomAccessHardwareRecord();

System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");

try// read a record and display

{

file.seek(0);

while (true)

{

do

{

record.read(file);

}

while (record.getRecordNumber() == 0);

// display record contents

System.out.printf("%-10d%-15s%-15d%10.2f\n",record.getRecordNumber(),

record.getToolName(), record.getQuantity(), record.getCost());

}// end while

}// end try

catch (EOFException eofException)// close file

{

return;// end of file was reached

}// end catch

catch (IOException ioException)

{

System.err.println("Error reading file.");

System.exit(1);

}// end catch

}// end method readRecords

}// end class FileEditor

-

// Exercise 14.11: TransactionProcessor.java

// A transaction processing program using random-access files.

import java.io.IOException;

import java.util.NoSuchElementException;

import java.util.Scanner;

import org.egan.RandomAccessHardwareRecord;

publicclass TransactionProcessor

{

private FileEditor dataFile;

private RandomAccessHardwareRecord record;

private MenuOption choices[] ={MenuOption.PRINT, MenuOption.UPDATE, MenuOption.NEW,

MenuOption.DELETE, MenuOption.END};

private Scanner input =new Scanner(System.in);

// get the file name and open the file

privateboolean openFile()

{

try// attempt to open file

{

// call the helper method to open the file

dataFile =new FileEditor("hardware.dat");

}// end try

catch (IOException ioException)

{

System.err.println("Error opening file.");

returnfalse;

}// end catch

returntrue;

}// end method openFile

// close file and terminate application

privatevoid closeFile()

{

try// close file

{

dataFile.closeFile();

}// end try

catch (IOException ioException)

{

System.err.println("Error closing file.");

System.exit(1);

}// end catch

}// end method closeFile

// create, update or delete the record

privatevoid performAction(MenuOption action)

{

int recordNumber = 0;// record number of record

String toolName;// tool name of the hardware instrument

int quantity;// total amount of items

double cost;// hareware tool price

int choice;// choose an update option

int newRecordNumber;// the updated record number

String newToolName;// the updated tool name

int newQuantity;// the updated quantity

double newCost;// the updated cost

try// attempt to manipulate files based on option selected

{

switch(action)// switch based on option selected

{

case PRINT:

System.out.println();

dataFile.readRecords();

break;

case NEW:

System.out.printf("\n%s%s\n%s\n%s","Enter record number,",

"tool name, quantity, and cost.","(Record number must be 1 - 100)","? ");

recordNumber = input.nextInt();// read record number

toolName = input.next();// read tool name

quantity = input.nextInt();// read quantity

cost = input.nextDouble();// read cost

dataFile.newRecord(recordNumber, toolName, quantity, cost);// create new record

break;

case UPDATE:

System.out.print("\nEnter record number to update (1 - 100): ");

recordNumber = input.nextInt();

record = dataFile.getRecord(recordNumber);

if (record.getRecordNumber() == 0)

System.out.println("Record does not exist.");

else

{

// display record contents

System.out.printf("%-10d%-12s%-12d%10.2f\n\n", record.getRecordNumber(),

record.getToolName(), record.getQuantity(), record.getCost());

System.out.printf("%s%s","\nEnter 1 to update tool name, ",

"2 to update quantity, or 3 to update cost : ");

choice = input.nextInt();

if (choice == 1)

{

System.out.print("Enter new record tool name : ");

newToolName = input.next();

dataFile.updateRecordToolName(recordNumber,newToolName);// update record

// tool name

// retrieve updated record

record = dataFile.getRecord(recordNumber);

// display updated record

System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),

record.getToolName(), record.getQuantity(), record.getCost());

}

elseif (choice == 2)

{

System.out.print("Enter new record quantity : ");

newQuantity = input.nextInt();

dataFile.updateRecordQuantity(recordNumber,newQuantity);// update record

// quantity

// retrieve updated record

record = dataFile.getRecord(recordNumber);

// display updated record

System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),

record.getToolName(), record.getQuantity(), record.getCost());

}

elseif (choice == 3)

{

System.out.print("Enter new record cost : ");

newCost = input.nextDouble();

dataFile.updateRecordCost(recordNumber,newCost);// update record cost

// retrieve updated record

record = dataFile.getRecord(recordNumber);

// display updated record

System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),

record.getToolName(), record.getQuantity(), record.getCost());

}

}// end else

break;

case DELETE:

System.out.print("\nEnter an account to delete ( 1 - 100): ");

recordNumber = input.nextInt();

dataFile.deleteRecord(recordNumber);// delete record

break;

default:

System.out.println("Invalid action.");

break;

}// end switch

}// end try

catch (NumberFormatException format)

{

System.err.println("Bad input.");

}// end catch

catch (IllegalArgumentException badRecord)

{

System.err.println(badRecord.getMessage());

}// end catch

catch (IOException ioException)

{

System.err.println("Error writing to the file.");

}// end catch

catch (NoSuchElementException elementException)

{

System.err.println("Invalid input. Please try again.");

input.nextLine();

}// end catch

}// end method performAction

// enable user to input menu choice

private MenuOption enterChoice()

{

int menuChoice = 1;

// display available options

System.out.printf("\n%s\n%s\n%s\n%s\n%s\n%s","Enter your choice",

"1 - List hardware records","2 - Update a hardware record",

"3 - Add a new hardware record","4 - Delete a hardware record","5 - End program\n?");

try

{

menuChoice = input.nextInt();

}

catch (NoSuchElementException elementException)

{

System.err.println("Invalid input.");

System.exit(1);

}// end catch

return choices[menuChoice - 1];// return choice from user

}// end enterChoice

publicvoid processRequests()

{

openFile();

// get user's request

MenuOption choice = enterChoice();

while (choice != MenuOption.END)

{

performAction(choice);

choice = enterChoice();

}// end while

closeFile();

}// end method processRequests

}// end class TransactionProcessor

-

// Exercise 14.11: TransactionProcessorTest.java

// Testing the transaction processor.

publicclass TransactionProcessorTest

{

publicstaticvoid main(String args[])

{

TransactionProcessor application =new TransactionProcessor();

application.processRequests();

}// end main

}// end class TransactionProcessorTest

-

Below is the sample data to be entered into the random input file hardware.dat :

-

Record ToolQuantityCost

NumberName

3 Sander18 35.99

19 Hammer128 10.00

26 Jigsaw1614.25

39 Mower1079.50

56 Saw8 89.99

76 Screwdriver236 4.99

81 Sledgehammer3219.75

88 Wrench 656.48

Message was edited by:

egan128

Message was edited by:

egan128

Message was edited by:

egan128

[39728 byte] By [egan128a] at [2007-10-3 3:23:20]
# 1

> Hi Does anyone know if I can modify the record number

> in the random access file hardware.dat for each

> hardware record each time and update it in

> hardware.dat to display it?

If the "record number" is data that is stored in the file, then you can modify it. More precisely: it is possible to modify it.

The rest of the question had too many incompatible verbs for me to understand it.

> Also why does it say

> "Record does not exist" if I modify the record number

> for a hardware and try to update it but could not

> find that record?

"Record does not exist" is a fairly reasonable error message for the situation where a program looks for a record but cannot find it. Are you asking why that particular lump of code actually does that?

(One thousand lines of code removed)

DrClapa at 2007-7-14 21:15:53 > top of Java-index,Java Essentials,New To Java...
# 2

Hi DrClap. How do you modifiy the record number in each of the hardware record?After modifying the record number in each hardware record, updating the record to modify for either record number, tool name, quantity or cost makes the each record does not exist. How do you make the record number that you modify exist? After modifying the record 3 to 12 in record : 3 Sander 18 35.99

and displaying : 12 Sander1835.99

. I type in 2 to update and type record number 12, the message record does not exist occurs, why is that?

egan128a at 2007-7-14 21:15:53 > top of Java-index,Java Essentials,New To Java...