Is there a way to add data into a RandomAccessFile using seek(long) without writing over the data at that position and beyond? For example:

public static void main(String[] args) throws Exception    {
    RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
    raf.writeBytes("Hello, World!");
    seek(2);
    raf.writeBytes("Goodbye, World!");
    raf.close();
}

Using that the file would read

HeGoodbye, World!

Is there a way to make it

HeGoodbye, World!llo, World

instead?

The way I was thinking isn't practical enough to use as it involved reading all the data from the desired position to the end and then writing it back into the file after the write("Goodbye, World!"); but in a large file that's not really possible.


So any ideas would be appreciated!

I'm pretty certain you have to read and re-write the data from the insertion point to EOF. How big is the file? There's no problem with (say) 100Mb reading the whole thing into memory, modfying it, the re-writing it.
If your data is more structured than the example the there may be a smarter way to organise it. Eg if consists of records with known formats, and you want to insert a whole record, you can structure the file with each record holding a pointer to the next logical record. Then you can add the new record to the physical end of the file and just overwrite a couple of pointer values to insert it in the right logical position.

Thanks for the reply.
Basically we're required to write every entry in a HashMap, simulating a simple database, to file in order that it is stored. The file size isn't known and should be able to (technically)hold up to Integer.MAX_VALUE entries. But I don't think that the lecturer will expect our implementation to hold that much!

The data is only the HashMap key and a String value. But I was wondering if there was a better way!

Just read & write the HashMap as a single Object using a single read/write call on Object input/output streams. Easy & fast.

Sorry I should have mentioned that I am required to use a RandomAccessFile and to update the file data each time the HashMap is changed ie. adding a new entry or removing an entry from the file. It's just an annoying assignment that has hardly any real-world application.

In that case I would go for the approach outlined in my previous post - chain the records together so you can insert physically at the end but logically in the middle.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.