Random access files

This program is supposed to retrieve data from TelephoneUI's JTextFields, store the data in a RandomAccessRecord class object record and call the write method of class RandomAccessRecord to output the data.
Two questions
Is there any way to check if the data was actually written to the file without writing a new class to read the file?
How can I make it so that the file-position pointer for object output start from byte 0 for the first record and move 94 bytes after each read? Right now the file-position pointer moves 94 bytes after each read but starts from 94.
public class WriteRandomFile extends JFrame {  
   private RandomAccessFile output;
   private TelephoneUI userInterface;
   private JButton enterButton, openButton;
   // set up GUI
   public WriteRandomFile()
      super( "Write to random access file" );
      // create instance of reusable user interface TelephoneUI
      userInterface = new TelephoneUI(4);  // four textfields
      getContentPane().add( userInterface,
         BorderLayout.CENTER );
      // get reference to generic task button doTask1 in TelephoneUI
      openButton = userInterface.getDoTask1Button();
      openButton.setText( "Open..." );
      // register listener to call openFile when button pressed
      openButton.addActionListener(
         // anonymous inner class to handle openButton event
         new ActionListener() {
            // allow user to select file to open
            public void actionPerformed( ActionEvent event )
               openFile();
         }  // end anonymous inner class
      ); // end call to addActionListener
      // register window listener for window closing event
      addWindowListener(
         // anonymous inner class to handle windowClosing event
         new WindowAdapter() {
            // add record in TelephoneUI, then close file
            public void windowClosing( WindowEvent event )
               if ( output != null )
                  addRecord();
               closeFile();
         }  // end anonymous inner class
      ); // end call to addWindowListener
      // get reference to generic task button doTask2 in TelephoneUI
      enterButton = userInterface.getDoTask2Button();
      enterButton.setText( "Enter" );
      enterButton.setEnabled( false );
      // register listener to call addRecord when button pressed
      enterButton.addActionListener(
         // anonymous inner class to handle enterButton event
         new ActionListener() {
            // add record to file
            public void actionPerformed( ActionEvent event )
               addRecord();
         }  // end anonymous inner class
      ); // end call to addActionListener
      setSize( 300, 150 );
      show(); 
   // enable user to choose file to open
   private void openFile()
      // display file dialog so user can select file
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setFileSelectionMode(
         JFileChooser.FILES_ONLY );
      int result = fileChooser.showOpenDialog( this );
      // if user clicked Cancel button on dialog, return
      if ( result == JFileChooser.CANCEL_OPTION )
         return;
      // obtain selected file
      File fileName = fileChooser.getSelectedFile();
      // display error if file name invalid
      if ( fileName == null ||
           fileName.getName().equals( "" ) )
         JOptionPane.showMessageDialog( this,
            "Invalid File Name", "Invalid File Name",
            JOptionPane.ERROR_MESSAGE );
      else {
         // open file
         try {
            output = new RandomAccessFile( fileName, "rw" );
            enterButton.setEnabled( true );
            openButton.setEnabled( false );
         // process exception while opening file
         catch ( IOException ioException ) {
            JOptionPane.showMessageDialog( this,
               "File does not exist",
               "Invalid File Name",
               JOptionPane.ERROR_MESSAGE );
   }  // end method openFile
   // close file and terminate application
   private void closeFile()
      // close file and exit
      try {
         if ( output != null )
            output.close();
           System.exit( 0 );
      // process exception while closing file
      catch( IOException ioException ) {
         JOptionPane.showMessageDialog( this,
            "Error closing file",
            "Error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 );
   // add one record to file
   public void addRecord()
      String fields[] = userInterface.getFieldValues();
      RandomAccessRecord record =
         new RandomAccessRecord();
      int count = 1;
      // ensure field has a value
      if ( ! fields[ TelephoneUI.LASTNAME ].equals( "" ) ) {
         // output values to file
         try {
               record.setFirstName( fields[ TelephoneUI.FIRSTNAME ] );
               record.setLastName( fields[ TelephoneUI.LASTNAME ] );
               record.setAddress( fields[ TelephoneUI.ADDRESS ] );
               record.setPhone( Integer.parseInt( fields[ TelephoneUI.PHONENUMBER ] ) );
                         count = count * 94;
                         output.seek( count );
               record.write( output );
            userInterface.clearFields();  // clear TextFields
         // process improper account number or balance format
         catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad account number or balance",
                   "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
         // process exceptions while writing to file
         catch ( IOException ioException ) {
            closeFile();
   }  // end method addRecord
   // execute application
   public static void main( String args[] )
      new WriteRandomFile();
}  // end class WriteRandomFile

This program is supposed to retrieve data from
TelephoneUI's JTextFields, store the data in a
RandomAccessRecord class object record and call the
write method of class RandomAccessRecord to output
the data.
Two questions
Is there any way to check if the data was actually
written to the file without writing a new class to
read the file? Why? If the io operations are not working (and not throwing exceptions) then you might as well give up.
>
How can I make it so that the file-position pointer
for object output start from byte 0 for the first
record and move 94 bytes after each read? Right now
the file-position pointer moves 94 bytes after each
read but starts from 94.Huh? It moves 94 and you want it to move 94?
Perhaps you are just looking for the getFilePointer() and seek() methods?
>
public class WriteRandomFile extends JFrame {
private RandomAccessFile output;
private TelephoneUI userInterface;
private JButton enterButton, openButton;
// set up GUI
public WriteRandomFile()
super( "Write to random access file" );
// create instance of reusable user interface
erface TelephoneUI
userInterface = new TelephoneUI(4);  // four
/ four textfields
getContentPane().add( userInterface,
BorderLayout.CENTER );
// get reference to generic task button doTask1
oTask1 in TelephoneUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open..." );
// register listener to call openFile when
e when button pressed
openButton.addActionListener(
// anonymous inner class to handle
to handle openButton event
new ActionListener() {
// allow user to select file to open
public void actionPerformed( ActionEvent
ActionEvent event )
openFile();
}  // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing
losing event
addWindowListener(
// anonymous inner class to handle
to handle windowClosing event
new WindowAdapter() {
// add record in TelephoneUI, then close
, then close file
public void windowClosing( WindowEvent
WindowEvent event )
if ( output != null )
addRecord();
closeFile();
}  // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2
oTask2 in TelephoneUI
enterButton =
tton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false );
// register listener to call addRecord when
d when button pressed
enterButton.addActionListener(
// anonymous inner class to handle
to handle enterButton event
new ActionListener() {
// add record to file
public void actionPerformed( ActionEvent
ActionEvent event )
addRecord();
}  // end anonymous inner class
); // end call to addActionListener
setSize( 300, 150 );
show(); 
// enable user to choose file to open
private void openFile()
// display file dialog so user can select file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this
( this );
// if user clicked Cancel button on dialog,
ialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File
Invalid File Name",
JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new RandomAccessFile( fileName,
e( fileName, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
// process exception while opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
}  // end method openFile
// close file and terminate application
private void closeFile()
// close file and exit
try {
if ( output != null )
output.close();
           System.exit( 0 );
// process exception while closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
// add one record to file
public void addRecord()
String fields[] =
ds[] = userInterface.getFieldValues();
RandomAccessRecord record =
new RandomAccessRecord();
int count = 1;
// ensure field has a value
if ( ! fields[ TelephoneUI.LASTNAME ].equals(
quals( "" ) ) {
// output values to file
try {
record.setFirstName( fields[
stName( fields[ TelephoneUI.FIRSTNAME ] );
record.setLastName( fields[
stName( fields[ TelephoneUI.LASTNAME ] );
record.setAddress( fields[
ddress( fields[ TelephoneUI.ADDRESS ] );
record.setPhone( Integer.parseInt(
teger.parseInt( fields[ TelephoneUI.PHONENUMBER ] )
                         count = count * 94;
                         output.seek( count );
record.write( output );
userInterface.clearFields();  // clear
);  // clear TextFields
// process improper account number or
number or balance format
catch ( NumberFormatException
Exception formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions while writing to file
catch ( IOException ioException ) {
closeFile();
}  // end method addRecord
// execute application
public static void main( String args[] )
new WriteRandomFile();
}  // end class WriteRandomFile

Similar Messages

  • 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
    public class HardwareRecord
      private int recordNumber;
      private String toolName;
      private int quantity;
      private double 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
      public void setRecordNumber(int number)
        recordNumber = number;
      } // end method setRecordNumber
      // get record number
      public int getRecordNumber()
        return recordNumber;
      } // end method getRecordNumber
      // set tool name
      public void setToolName(String tool)
        toolName = tool;
      } // end method setToolName
      // get tool name
      public String getToolName()
        return toolName;
      } // end method getToolName
      // set quantity
      public void setQuantity(int amount)
        quantity = amount;
      } // end method setQuantity
      // get quantity
      public int getQuantity()
        return quantity;
      } // end method getQuantity
      // set cost
      public void setCost(double price)
        cost = price;
      } // end method setCost
      // get cost
      public double 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;
    public class RandomAccessHardwareRecord extends HardwareRecord
      public static final int 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
      public void 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[] = new char[15], temp;
        for(int count = 0; count < name.length; count++)
          temp = file.readChar();
          name[count] = temp;
        } // end for
        return new String(name).replace('\0',' ');
      } // end method readName
      // write a record to specified RandomAccessFile
      public void 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
      private void 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;
    public class CreateRandomFile
      private static final int NUMBER_RECORDS = 100;
      // enable user to select file to open
      public void 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
    public class CreateRandomFileTest
       // main method begins program execution
       public static void 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.
    public enum MenuOption
      // declare contents of enum type
      PRINT(1),
      UPDATE(2),
      NEW(3),
      DELETE(4),
      END(5);
      private final int value; // current menu option
      MenuOption(int valueOption)
        value = valueOption;
      } // end MenuOptions enum constructor
      public int 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;
    public class 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
      public void 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)
          throw new 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
      public void updateRecordToolName(int recordNumber, String newToolName)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new 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
      public void updateRecordQuantity(int recordNumber, int newQuantity)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new 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
      public void updateRecordCost(int recordNumber, double newCost)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new 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
      public void newRecord(int recordNumber, String toolName, int quantity, double cost)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() != 0)
          throw new 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
      public void deleteRecord(int recordNumber) throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new 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
      public void 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;
    public class 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
      private boolean 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.");
          return false;
        } // end catch
        return true;
      } // end method openFile
      // close file and terminate application
      private void 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
      private void 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());
                else if (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());
                else if (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
      public void 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.
    public class TransactionProcessorTest
      public static void 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                     Tool                        Quantity                Cost
    Number                   Name                
       3                      Sander                    18                         35.99
      19                      Hammer                128                      10.00
      26                      Jigsaw                   16                        14.25
      39                      Mower                    10                        79.50
      56                      Saw                        8                          89.99
      76                      Screwdriver            236                      4.99
      81                      Sledgehammer       32                        19.75
      88                      Wrench                      65                        6.48Message was edited by:
    egan128
    Message was edited by:
    egan128
    Message was edited by:
    egan128

    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)

  • How to read a mixed text and binary random-access file?

    I have a PDF file which I want to decode. The format is a mixture of binary data and text. What I need is to position the file to a particular position, and then to read from that point as a stream either a set of binary bytes or straight ASCII text. I can't see how to do this (if in fact it's possible).
    I can open the file as a SeekableByteChannel and position it, but opening a stream repositions the file to the beginning - just what I don't want.
    Is there any way of opening a stream from part-way through a file?

    I think that I gave this topic a rather misleading title. What it really should be is "How to turn a random access file into a stream"?
    I realise that I can open an InputStream and skip the relevant number of characters - but this is highly inefficient on a large file where I will skipping about within the file. I need a stream so that I can apply other stream functions to it - buffering in memory will I suspect be too big.

  • How to use random access file to access file in disk?

    I have tried to use random access file stream to access the some files saved in disk, but not very successful. I want to know how I can find a particular file in the disk with file locator or sth else.
    Suggestion is highly welcomed, if you have codes to put, I will test it.

    The scenerao is:
    create a randomAccessfile
    write 100 blank records( for future use)
    open this file
    write data to the records inside file
    close the file.
    I will try to put a testing code for you later on.

  • Random Access File not working, Need Help!!!!

    I am having trouble creating and displaying a Random Access File for hardware tools. I have included the code below in eight files:
    // Exercise 14.11: HardwareRecord.java
    package org.egan; // packaged for reuse
    public class HardwareRecord
      private int recordNumber;
      private String toolName;
      private int quantity;
      private double 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
      public void setRecordNumber(int number)
        recordNumber = number;
      } // end method setRecordNumber
      // get record number
      public int getRecordNumber()
        return recordNumber;
      } // end method getRecordNumber
      // set tool name
      public void setToolName(String tool)
        toolName = tool;
      } // end method setToolName
      // get tool name
      public String getToolName()
        return toolName;
      } // end method getToolName
      // set quantity
      public void setQuantity(int amount)
        quantity = amount;
      } // end method setQuantity
      // get quantity
      public int getQuantity()
        return quantity;
      } // end method getQuantity
      // set cost
      public void setCost(double price)
        cost = price;
      } // end method setCost
      // get cost
      public double 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;
    public class RandomAccessHardwareRecord extends HardwareRecord
      public static final int SIZE = 72;
      // 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
      public void 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[] = new char[15], temp;
        for(int count = 0; count < name.length; count++)
          temp = file.readChar();
          name[count] = temp;
        } // end for
        return new String(name).replace('\0',' ');
      } // end method readName
      // write a record to specified RandomAccessFile
      public void 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
      private void 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;
    public class CreateRandomFile
      private static final int NUMBER_RECORDS = 100;
      // enable user to select file to open
      public void 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
    public class CreateRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateRandomFile application = new CreateRandomFile();
         application.createFile();
       } // end main
    } // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.11: WriteRandomFile.java
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.RandomAccessHardwareRecord;
    public class WriteRandomFile
      private RandomAccessFile output;
      private static final int NUMBER_RECORDS = 100;
      // enable user to choose file to open
      public void openFile()
        try // open file
          output = new RandomAccessFile("hardware.dat","rw");
        } // end try
        catch (IOException ioException)
          System.err.println("File does not exist.");
        } // end catch
      } // end method openFile
      // close file and terminate application
      public void closeFile()
        try // close file and exit
          if (output != null)
            output.close();
        } // end try
        catch (IOException ioException)
          System.err.println("Error closing file.");
          System.exit(1);
        } // end catch
      } // end method closeFile
      // add records to file
      public void addRecords()
        // object to be written to file
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        int recordNumber = 0;
        String toolName;
        int quantity;
        double cost;
        Scanner input = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
         "To terminate input, type the end-of-file indicator ",
         "when you are prompted to enter input.",
         "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
         "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s %s\n%s", "Enter record number (1-100),",
          "tool name, quantity and cost.","? ");
        while (input.hasNext())
          try  // output values to file
            recordNumber = input.nextInt();  // read record number
            toolName = input.next();         // read tool name
            quantity = input.nextInt();      // read quantity
            cost = input.nextDouble();       // read cost
            if (recordNumber > 0 && recordNumber <= NUMBER_RECORDS)
              record.setRecordNumber(recordNumber);
              record.setToolName(toolName);
              record.setQuantity(quantity);
              record.setCost(cost);         
              output.seek((recordNumber - 1) *   // position to proper
               RandomAccessHardwareRecord.SIZE); // location for file
              record.write(output);
            } // end if
            else
              System.out.println("Account must be between 0 and 100.");
          } // end try   
          catch (IOException ioException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input.nextLine();  // discard input so enter can try again
          } // end catch
          System.out.printf("%s %s\n%s","Enter record number (1-100),",
            "tool name, quantity and cost.", "? ");
        } // end while
      } // end method addRecords
    } // end class WriteRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: WriteRandomFileTest.java
    // Testing class WriteRandomFile
    public class WriteRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         WriteRandomFile application = new WriteRandomFile();
         application.openFile();
         application.addRecords();
         application.closeFile();
       } // end main
    } // end class WriteRandomFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.11: ReadRandomFile.java
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import org.egan.RandomAccessHardwareRecord;
    public class ReadRandomFile
      private RandomAccessFile input;
      // enable user to select file to open
      public void openFile()
        try // open file
          input = new RandomAccessFile("hardware.dat","r");
        } // end try
        catch (IOException ioException)
          System.err.println("File does not exist.");
        } // end catch
      } // end method openFile
      // read and display records
      public void readRecords()
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
        try // read a record and display
          while(true)
            do
              record.read(input);
            }while (record.getRecordNumber() == 0);
            // display record contents
            System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
             record.getToolName(), record.getQuantity(), record.getCost());
          } // end while
        } // end try
        catch (EOFException eofException)
          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
      // close file and terminate application
      public void closeFile()
        try // close file and exit
          if (input != null)
            input.close();
        } // end try
        catch (IOException ioException)
          System.err.println("Error closing file.");
          System.exit(1);
        } // end catch
      } // end methode closeFile
    } // end class ReadRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: ReadRandomFileTest.java
    // Testing class ReadRandomFile
    public class ReadRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         ReadRandomFile application = new ReadRandomFile();
         application.openFile();
         application.readRecords();
         application.closeFile();
       } // end main
    } // end class ReadRandomFileTest-------------------------------------------------------------------------------------------------
    Below is the sample data to be inputted in the random file:
    Record Tool Name Quantity Cost
    Number
    3 Sander 18 35.99
    19 Hammer 128 10.00
    26 Jigsaw 16 14.25
    39 Mower 10 79.50
    56 Saw 8 89.99
    76 Screwdriver 236 4.99
    81 Sledgehammer 32 19.75
    88 Wrench 65 6.48

    I have managed to fix your program.
    The solution
    The records are sized by the various Writes that occur.
    A record is an int + 15 chars + int + double.
    WriteInt writes 4 bytes
    WriteChar (Called by WriteChars) write 2 bytes
    WriteDouble writes 8 bytes.
    (In Java 1.5 )
    4 bytes + 30 Bytes + 4Bytes + 8 Bytes. = 46 Bytes.
    The details are in the API for Random Acces Files at
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/RandomAccessFile.html
    The code for RandomAccessHardwareRecord line
    public statis final int SIZE = 72needs to have the 72 changed to 46
    This should make your code work.
    I have hacked around with some other bits and will send you my code if you want but that is the key. The asnwers you were getting illustrated a bunch of bytes being read as (say) an int and beacuse of the wrong record length, they were just a bunch of 4 bytes that evaluated to whetever was at that point in the file.
    When the record was written the line
    output.seek((recordNumber -1 ) * RandomAccessHardwareRecord.SIZE);had SIZE as 72 and so the seek operation stuck the file pointer in the wrong place.
    This kind of stuff is good fun and good learning for mentally getting a feel for record filing but in real problems you either serialize your objects or use XML (better) or use jdbc (possibley even better depending on what you are doing).
    I would echo sabre comment about the program being poor though because
    If the program is meant to teach, it is littered with overly complex statements and if it is meant to be a meaningful program, the objects are too tied to hardware and DAO is the way to go. The problem that the program has indicates that maybe it is maybe fairly old and not written with java 2 in mind.
    As for toString() and "Yuk"
    Every class inherits toString() from Object. so if you System.out.println(Any object) then you will get something printed. What gets printed is determined by a complex hieracrchy of classes unless you overRide it with your own method.
    If you use UnitTesting (which would prevent incorrect code getting as far as this code did in having an error), then toString() methods are really very useful.
    Furthermore, IMO Since RandomAccessHardwareRecord knows how to file itself then I hardly think that knowing how to print itself to the console is a capital offence.
    In order to expand on the 72 / 46 byte problem.
    Message was edited by:
    nerak99

  • Random access file in process visability

    I want to use a file in a single process with single writer or multi readers mutual exclusion, for that purpose I use number of RandomAccessFile instances over the same file which are open in read mode and are used concurrently. I also have a single RandomAccessFile open in "rw" mode which updates the file (not when it is being actively read).
    I do not close the Random Access File handles at any point.
    I wanted to know if the data which is being written to the file with the RandomAccessFile in rw mode will always be visible to the readers after the the write is complete?
    (I am not using rws mode for performance issues, only for these readers which are in the same process).
    Thanks
    Eitan

    Looking at FileChannel it has the following part in its documentation:
    * The view of a file provided by an instance of this class is guaranteed
    * to be consistent with other views of the same file provided by other
    * instances in the same program. The view provided by an instance of this
    * class may or may not, however, be consistent with the views seen by other
    * concurrently-running programs due to caching performed by the underlying
    * operating system and delays induced by network-filesystem protocols. This
    * is true regardless of the language in which these other programs are
    * written, and whether they are running on the same machine or on some other
    * machine. The exact nature of any such inconsistencies are system-dependent
    * and are therefore unspecified.
    This looks exactly like the guarantee I need, now I've looked into RandomAccessFile.getChannel() implementation and it holds a single member of FileChannel which is initialized on demand and the next calls will return the same instance.
    So the only way I see to create multiple FileChannel instances over the same file is to open multiple RandomAccessFile instances over that file and use getChannel() on each of these instances. Since FileChannel does provide this guarantee I tend to believe it relies upon a guarantee that RandomAccessFile provide, otherwise it would need some mechanism to identify that different FileChannel instances over different RandomAccessFile instances are actually over the same file in order to provide the specified guarantee.
    What do you think?

  • Serialize tree in random access file

    I have a tree of objects, which are to be serialized. After deserialization,
    each object has to know its children and its parent. Each object need not know its sibling. There are no lateral references. The number of objects in the tree will be around 2000. The depth of tree is 7. Different parts of the tree will be saved and read at different points of time in the application. While the application is running, many of the objects in the tree keep undergoing changes which have to be saved intermittantly.
    I would like to use a random access file. But I have no clue how to serialize a tree of objects in a random access file which will meet the above mentioned requirements.
    I would be thankful if I could get an idea to implement.

    I have a tree of objects, which are to be serialized.
    After deserialization,
    each object has to know its children and its parent.
    Each object need not know its sibling. There are no
    lateral references. The number of objects in the tree
    will be around 2000. The depth of tree is 7.
    Different parts of the tree will be saved and read at
    different points of time in the application. This is an issue. When you Serialize something you serialize the entire object, not a part of it. If you're doing this then you're no longer talking about Serializing a Tree, you're talking about serializing some other thing that represents part of the tree.
    While
    the application is running, many of the objects in
    the tree keep undergoing changes which have to be
    saved intermittantly.
    I would like to use a random access file. But I have
    no clue how to serialize a tree of objects in a
    random access file which will meet the above
    mentioned requirements.
    I would be thankful if I could get an idea to
    implement.If you can come up with a "savable" representation of your tree that allows you to calculate where, in a file, a given part would be then you could use RandomAccessFile to read/write the thing. Just walk through your tree and seek to where you need to go in the file, then read/write the node.
    I hope that made sense
    Lee

  • Writing data in Random Access File

    I was reading something about Random Access File coz I wanted to practice file handling in java. like, writing a data in a random access file, deleting the stored data, updating the stored data and search for a specific data.. I wasn't able to understand the example because the book gave a large program and it's not explained in detail. Is there any good tutorials that you could recommend for me?

    http://www.google.com/search?q=java+RandomAccessFile+example&hl=en&sourceid=gd&rls=GGLD,GGLD:2008-06,GGLD:en
    How did we get anything done before google?

  • Random access file in a midlet

    Hi, I'm trying to develop a small dictionary for MIDP2.0/CLDC1.0, so I need to random access a data file in an efficient way. MIDP API itself only provides a sequential access input stream. What is the best way for me to implement a file input stream that supports random access? Thanks a lot!

    Hi!
    There's nothing like RandmAccessFile in midlets, but there is a way, you can read (only!) a file from jar.
    Here's the code:
    InputStream is = this.getClass().getResourceAsStream("<path_to_the_file>");
    DataInputStream dis = new DataInputStream(is);Then you can read the stream with any of the metods provided.

  • How to change the file pointer in random access file?

    I have a file, now I want to add a line at both the beginning and ending of the file. Should I use random access in this case? How can I move the pointer to the end of the file in that case? Thanks!
    ruuram

    I have a file, now I want to add a line at both the
    beginning and ending of the file. Should I use random
    access in this case?That's up to you. RandomAccessFile doesn't allow you to insert data at the beginning of the file, though.
    How can I move the pointer to the
    end of the file in that case? Thanks!
    file.seek(file.length())

  • Printing to the end of a Random Access file with FileOutputStream

    I need to use FileOutputStream or anything else to print to a text file. However I need to print to the "end" of the file and not write over existing content. Anybody, given the following how would I append the file "myFile.txt"? The code below writes over existing data in the file.
    import java.io.*
    class FileOutputDemo
    public static void mani( String argsv[])
    FileOutputStream out;
    PrintStream p;
    try
    out= new FileOutputStream("myFile.txt");
    p=new PrintStream( out ) ;
    p.println("Write this line of text to the end of the file");
    p.close();
    catch(Exception e) {*Do something */}

    One way is to use the RandomAccessFile class methods to append to the end of a file. Use the seek and length methods to go to the end of the file and use the appropriate method to write your data. Something like this:
    try {
    RandomAccessFile logFile=
    new RandomAccessFile("myFile.txt", "rw");
    logFile.seek(logFile.length());
    logFile.writeBytes(
    args[0]+"\n");
    catch (Exception e) {
    System.err.println("Error!");
    HTH

  • Moving data in random access file

    Hi All
    I am back again with the same query of RandomAccessFile.
    I want to move data in the by n bytes. How do I do this. Like I want to add data somewhere in middle of file. I am reaching at the point using seek() method and writing the data also. But the next line is getting overwritten. So I want to moves the data in file first and write my data.
    Please help me with logic or Code sniippet. I am struggling with this for past 2 weeks.
    Thanks in Advance
    With regards
    Shashi

    RandomAccessFile doesn't offer an insert facility, so
    you'll need to work around, such as create a
    temporary copy of the file by writing the file's
    head, your data to be inserted, and the file's tail,
    then delete the old file and rename the copy.When you stare at this a bit, you'll see this post is actually saying
    the same as mine :-)

  • Error with TimerTask and Random Access File in a Thread

    Hi all,
    Why I have this error?
    unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at line which contains:
    RandomAccessFile raf = new RandomAccessFile(f, "r");It does not work neither "Add Throws Clause" or "Surrond with Try / Catch"
    I am sending the full Java code. Thanks in advance.
    package voip;
    import java.io.*;
    import java.util.*;
    public class parseRTCP extends Thread {
      int delay = 2000; // delay for 2 sec.
      int period = 5000; // repeat every 5 sec.
      Timer timer = new Timer();
      public void run() {
        row = 0;
        System.out.println("Wait please!");
        timer.scheduleAtFixedRate(new TimerTask() {
          File f = new File("d:\\project\\java\\test.txt");
          RandomAccessFile raf = new RandomAccessFile(f, "r");
          public void run() {
            Calendar cal = new GregorianCalendar();
            int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
            int min = cal.get(Calendar.MINUTE); // 0..59
            int sec = cal.get(Calendar.SECOND); // 0..59
            System.out.println(hour24 + ":" + min + " " + sec + "s");
              String line = "";
              // Read all the text file
              try {
                while ( (line = raf.readLine()) != null) {
                  System.out.println(line);
              catch (IOException ex) {
        }, delay, period);
    }

    > It's a silly error but I don't know the
    answer.
    See reply #4, or resign yourself to not knowing the
    answer for eternity.I understand what are you meaning.
    >
    In case the hint's not big enough: POST THE EXACT
    TEXT AND STACK TRACE OF THE ERROR MESSAGE WHEN YOU
    TRY TO SURROUND "RandomAccessFile raf = new
    RandomAccessFile(f, "r");" WITH A TRY/CATCH BLOCK.2 error messages:
    illegal start type at line 20 (20:7)
    <identifier> expected at line 42 (42:8)
    line 20 --> try {
    line 42 --> } // end of public void run
    Java code:
    package voip;
    import java.io.*;
    import java.util.*;
    public class parseRTCP
        extends Thread {
      int delay = 2000; // delay for 2 sec.
      int period = 5000; // repeat every 5 sec.
      Timer timer = new Timer();
      public void run() {
        System.out.println("Wait please!");
        timer.scheduleAtFixedRate(new TimerTask() {
          File f = new File("d:\\project\\java\\test.txt");
          try { // ERROR!!
            RandomAccessFile raf = new RandomAccessFile(f, "r");
          } // end of try
          catch (FileNotFoundException ex) {
          } // end of catch
          public void run() {
            Calendar cal = new GregorianCalendar();
            int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
            int min = cal.get(Calendar.MINUTE); // 0..59
            int sec = cal.get(Calendar.SECOND); // 0..59
            System.out.println(hour24 + ":" + min + " " + sec + "s");
            String line = "";
            // Read all the text file
            try {
              while ( (line = raf.readLine()) != null) {
                System.out.println(line);
              } // end of while
            } // end of try
            catch (IOException ex) {
            } // end of catch
          } // end of public void run ERROR!!
        }, delay, period); // end of TimerTask
      } // end of public void run
    } // end of public class>
    Or have you not tried that yet?I have tried.
    Your replies and time so far are much appreciated (the same for
    everyone else who has helped),
    Many thanks,
    David

  • Random access file with object stream

    Hi All,
    I have saved some objects in a file using object stream. While reading the sequential read is possible for me. I want to reduce the overhead of reading whole file for getting one specific object details. Is there any way in which we can implement RandomAccessFile with object stream? or is there any other alternative of reaching specific object in the file without seqential read?

    is there any
    other alternative of reaching specific object in the
    file without seqential read?Write the objects to a database.

  • Random Access File Help!!!!!!!!

    I'm using randomaccessfile. I need some help with reading the file though. Whoever can help me with this can have my 10 buck things. Ok here is my situation: I made a store gift card type program. I wrote multiple writeUTF into the file. I need to read the file and place what was read into different strings. Here is my read code:
    package happycoffee;
    import java.io.*;
    public class FileReader
    public void fileReaderMethod(String cardTemp, String pinTemp, String balanceTemp,
    String firstName, String lastName, String customerStreet, String customerCity,
    String customerState, String customerZip, String datePurchased, String customerIncome)
    try {
    String dataPosition;
    int data = 0;
    RandomAccessFile cardStore = new RandomAccessFile("datafile", "r");
    //Get the position of the data to read.
    //dataPosition = cardStore.readLong();
    dataPosition = cardStore.readUTF();
    System.out.println(dataPosition); //DELETE THIS LINE!!!!!!!!!!!!!!!!!!!!!!!!
    //Go to that position.
    //Read the data.
    data = cardStore.readUTF();
    cardStore.close();
    //Tell the world.
    //System.out.println("The data is: " + data);
    } catch (FileNotFoundException e) {
    System.err.println("This shouldn't happen: " + e);
    } catch (IOException e) {
    System.err.println("Writing error: " + e);
    Please help!! I gotta submit this by midnight!!!

    You can try and use string tokenizer to make tokens out of a single line.
    That way you can seperate them. See the string tokenizer docs .
    c123456789321 999999 100 Susan Jackson
    124 Happy Ln.
    Happyville CA 93121 5-19-03 1
    Above is what is currently in the file. It has a
    separator between each variable that I put in. Is
    there a way to put thos into separate variables?

Maybe you are looking for

  • Help with Match Calculations

    I have a simple form on a web page for associaiton members to order lapel pins. I want to provide a toal cost of the order but I can't for the life of me get anything to multiply the value in a text fiels by a constant number ($5.00). I found some Ja

  • Proper use of htmldb_util.set_session_state

    Looking for a way to set a page variable from a trigger. I have an app that needs a variable set from within an insert trigger. I would like to let the user see the value of that variable on the page after the insert is complete. Can I use htmldb_uti

  • Using int and SERIAL as datatypes in cmp Beans.

    Hi I�m using a postgresql database with my appserver 7. I have some trouble using some of the �normal� db functions. Ex SERIAL (or auto_number). Is it possible to create a create method in a cmp bean using SERIAL? I�m using SERIAL as the primary key.

  • How a customer return can be handled?

    Hi Everyone, I have created a customer return notification with 10 quantities with a single return ID (generated) Under sales work center the sales employee need to confirm the return against created sales order either 1. with credit memo (5 quantiti

  • Photoshop cs5 blinking screen, freezing, shutting down

    Hi,    I'm a photographer and I recently purchased an 8 core Mac Pro 16 Ram with a standard GT 120 video card (Nvidia Gee Force).  When I purchased the computer, I also purchased photoshop cs5.  I am running into issues when editing my images in cs5.