Question

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();

        }
Was it helpful?

Solution

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top