Hello All,

I really hope that you can help me. I am working on a program that will read a randomaccess file's contents and store the contents into an array. It will then update the array and write it back into the randomaccess file. I have the following two methods and am not sure how to get them to read from a Randomaccessfile into an array and from an array back to a randomaccessfile.

/**
      Writes a savings account record to the data file
      @param n the index of the account in the data file
      @param account the account to write
   */
   public void write(int n, BankAccount account)
         throws IOException
   {  
      file.seek(n * RECORD_SIZE);
      file.writeInt(account.getAccountNumber());
      file.writeDouble(account.getBalance());
      byte[] buf = new byte[BankAccount.SIZE];
      file.write(buff);
   }
	
	
	
 /**
      Reads a savings account record.
      @param n the index of the item in the data file
      @return a savings account object initialized with the file data
   */
   public BankAccount read(int n)
         throws IOException
   {  
      file.seek(n * RECORD_SIZE);      
      int accountNumber = file.readInt();
      double balance = file.readDouble();
      byte[] buf = new byte[BankAccount.SIZE];
      file.readFully(buf);
      return new BankAccount(accountNumber, balance);
   }

Any help will be appreciated.
Thanks, Kim

I presume that the RECORD_SIZE=13 bytes. 4 bytes for integer + 8 bytes for double + 1 byte for buf array (BankAccount.SIZE).

public void write(int n, BankAccount account)
         throws IOException
   {  
      n--;   
      file.seek(n * RECORD_SIZE);
      file.writeInt(account.getAccountNumber());
      file.writeDouble(account.getBalance());
      byte[] buf = new byte[BankAccount.SIZE];
      file.write(buff);
   }
	
	
	
 /**
      Reads a savings account record.
      @param n the index of the item in the data file
      @return a savings account object initialized with the file data
   */
   public BankAccount read(int n)
         throws IOException
   {  
      n--;      
      file.seek(n * RECORD_SIZE);      
      int accountNumber = file.readInt();
      double balance = file.readDouble();
      byte[] buf = new byte[BankAccount.SIZE];
      file.read(buf,0,buf.length);
      return new BankAccount(accountNumber, balance);
   }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.