Saturday, 24 August 2013

Java Fixed Length Random Access Files

Java Fixed Length Random Access Files

I just watched a tutorial on youtube showing how to create fixed length
random access files in java. I am slightly confused with the concept of
the writeBytes method within the RandomAccessFile class.
// Create an instance of the RandomAccessFile class
RandomAccessFile raf = new RandomAccessFile("RAF1.dat", "rw");
// Get the length of the file so new entries
// Are added at the end of the file
raf.seek(raf.length());
// Max input length of the persons name
int recordLength = 20;
// Each record will have a byte length of 22
// Because writeUTF takes up 2 bytes
int byteLength = 22;
// Just a random name to stick in the file
String name = "John";
// Write the UTF name into the file
raf.writeUTF(name);
// Loop through the required whitespace to
// Fill the contents of the record with a byte
// e.g recordLength - nameLength (20 - 4) = 16 whitespace
for (int i = 0; i < recordLength - name.length(); i++) {
raf.writeByte(10);
}
Above is the code I use to write to the Random Access File. As you can see
I am using raf.writeByte(10); in order to fill the whitespace in the
record.
raf.writeByte(10); Stores the following in the file:
&#1024;…œ¦&#2570;&#2570;&#2570;&#2570;&#2570;&#2570;&#2570;&#2570;
However when I change raf.writeByte(10); to raf.writeByte(0); and create a
new file...
raf.writeByte(0); Stores the following in the NEW file: John
You may not be able to see it correctly here but there is whitespace after
John and the name is actually readable.
Could you guys please explain why there is such a difference in using 0
bytes and 10 bytes?? Also could you please suggest any improvements I
could make to the code.
Thanks a lot, I appreciate the help :).

No comments:

Post a Comment