• Post Reply Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile  RSS feed

 
Gary Foster
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, im very new at this, and i've hit a road block. In a RAF i am holding data such as Name, address, DoB, phone number... etc. I have worked a way of navigating and adding the data into the file. The method of adding is shown below. Now i've come to a point where i want to ammend or change specific parts of a record within the file, and im a little unsure where to go from here, several textbooks haven't been helpful.

---Code for Adding (Error handling code is in too)---
if (e.getSource() == jbtAdd)
{
Account account = accountPanel.getAccount();
try
{
raf.seek(raf.length());
account.writeAccount(raf);
}
catch(IOException ex)
{
System.out.print("Cannot Add" );
}
}

Account is the name of a seperate class in my program. raf is the RandomAccessFile variable.

Thanks for any helpfull feedback!

Gary
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
RandomAccessFile is a rather low-level class and only provides ways to write primitives (float, double etc.) or byte arrays. If you want to use RandomAccessFile, you probably want to get your Account data into the form of a stream of bytes (maybe serialise it to a ByteArrayOutputStream), then write those bytes to the file.

However, if you only ever want to append to the end of the file, and never need to modify records part-way through the file (tricky - what do you do if there's not enough space to write the modified record?), then perhaps you do not need to use RandomAccessFile. Both FileWriter and FileOutputStream let you append to the end of a file. It's easier to write high-level data to a Writer or an OutputStream than to a RandomAccessFile.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the modification of records inside a RAF requires that you can locate the record exactly and that when writing you never write over the next record in the file. If you don't write exactly the correct number of bytes, the file gets corrupted.
You can either use a constant record size that never varies or have some independent record of start points and record sizes.
Bill
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!