简体   繁体   中英

Writing data to a file using RandomAccessFile

I am writing to a file using RandomAccessFile.The data(fields) are stored in fixed field length,eg 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,ie,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();

        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM