0

I am writing to a file using RandomAccessFile.The data(fields) are stored in fixed field length,e.g every field would alloted space of 16 bytes.I write something by placing the pointer to the appropriate position using seek(). Problem comes when I overwrite some fields,i.e,if "Bangalore" was stored earlier and if overwrite it with "Delhi" the result is "Delhilore". How do I erase "Bangalore" completely prior to writing "Delhi"?

If value is the String I want to write and length is the fixed field length(16)

        byte[] b=new byte[length];

        b=value.getBytes();

        try 
        {
            database.seek(offset);
            database.write(b);


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
Sameer Sarmah
  • 1,052
  • 4
  • 15
  • 33
  • 1
    you need to write full 16 bytes chunks to overwrite the old value. – kofemann Mar 14 '14 at 08:00
  • Given what you do, it'd be better if you used a file mapping; it would allow all those syscalls which you currently use. Basically, at a minimum you have a `seek()` and a `write()` each time you write a record. Using a mapping would avoid those two – fge Mar 14 '14 at 08:03
  • @tigran : byte[] b=new byte[length]; and database.write(b); should do that right? or do I need to add more code in order to write the whole 16 bytes. – Sameer Sarmah Mar 14 '14 at 08:07
  • 1
    Your current code does not work. You reassign b immediately afterwards to `value.getBytes()`. – fge Mar 14 '14 at 08:08

1 Answers1

0

You need to overwrite the full 16 bytes. An example of how to do that would be:

ByteBuffer buf = ByteBuffer.allocate(16);
buf.put(value.getBytes("UTF-8"));
database.seek(offset);
database.write(buf.array());

This will write trailing zeroes after the record contents.

Note however that for each record you write, this involves two system calls which you can avoid if you use a memory mapping of the file. See FileChannel.map().

fge
  • 119,121
  • 33
  • 254
  • 329
  • :How to write String "1" as byte array.whenever I use ByteBuffer buf =ByteBuffer.allocate(RECORD_FLAG_BYTES); buf.put(deleteFlag.getBytes("UTF-8")); database.write(buf.array()); it writes 49. – Sameer Sarmah Mar 14 '14 at 10:54