Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random access files.... problems appending to one

Status
Not open for further replies.

Maldini

Technical User
Nov 10, 2002
55
GB
I'm trying out the random access file function right now, but seem to be having a problem appending a new 'record' to the file. The problem arises when I try to 'pad' up the data I am appending, so that it makes up the required length for ta record.

Code:
RandomAccessFile rf = new RandomAccessFile(data, "rw");
rf.seek(rf.length());
rf.writeUTF("message here it is"+"\n");
String space = pad(" ",15);
String res = space.concat("abc");
rf.seek(rf.length());
rf.writeUTF(res+"\n");
rf.seek(rf.length());
rf.writeUTF(res+"\n");

public static String pad(String p, int n)
{
	if (n > 1) return(p+pad(p,--n));
	return(p);
}

For some strange reason, if I just append the first two, its ok, the writing to UTF is done perfectly to file. However, once the third is written, the file goes all over the place, fails to take into account the \n character.

Anyone know how to fix this?

Many thx.
Maldini
 
I ran your code and it worked fine. However, you should realize that it's also writing two extra bytes for each line. Here is a hex dump of the output file:

Code:
00    00 13 6D 65 73 73 61 67 65 20 68 65 72 65 20 69    .message here i
16    74 20 69 73 0A 00 13 20 20 20 20 20 20 20 20 20    t is..         
32    20 20 20 20 20 20 61 62 63 0A 00 13 20 20 20 20          abc..    
48    20 20 20 20 20 20 20 20 20 20 20 61 62 63 0A                  abc.

As you can see, a 00 byte and a 13 byte precede each record. Are you taking these into account?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top