Insert data into file without reading entire file into Ram
Hi all,
I'm having an "assignment" in which one criterion is :
- Inserting data into an ordered sequential file without reading the entire file into RAM
I don't know how to this. Could you show me how to write methods/API/code in Java, anything is fine with me.
Just to add some details, the files are created using RandomAccessFile, for example:
cD = new RandomAccessFile("customer.txt","rw");
However, by inititalizing cD, I'm actually reading the entire file. So may be someone can show me how to access arbitary files without the need to actually read the entire file
Tks a lot :)
tungnk1993
Junior Poster in Training
95 posts since May 2010
Reputation Points: 6
Solved Threads: 7
You can read any part of a file with RandomAccessFile.
However if you want to insert data into the file (and not just add to the end) and make the file larger, you will have to read all of the file's bytes so that the bytes after the insert point are moved down by the number of bytes the file changes in size.
For example, say these letters are the bytes in a file: ABCD and you want to insert an F after the A, that means the BCD have to be read in and rewritten in new locations following the F to get: AFBCD
NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
So if I only want to add to the end of the file, could you show me the code in Java to do that ?
tungnk1993
Junior Poster in Training
95 posts since May 2010
Reputation Points: 6
Solved Threads: 7
You can open a file in append mode if that's all you need.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073