In my project, we are writing a file using DataOutputStream
. We are writing different data types like short, byte, int and long and we are using respective methods in DataOutputStream
like writeShort()
, writeByte()
etc.
Now, I want to edit one record in this file at a particular offset. I know the offset from which that record starts but I am not sure what is the right approach of writing to the file because only method in DataOutputStream
supporting offset is the one which takes byte[]
.
I want to write the whole record which is a combination of different data types as mentioned above.
Can someone please tell me what is the correct approach for this?
In your case, you should use RandomAccessFile
in order to read and/or write some content in a file at a given location thanks to its method seek(long pos)
.
For example:
try (RandomAccessFile raf = new RandomAccessFile(filePath, "rw")) {
raf.seek(offset);
// do something here
}
NB: The methods writeShort()
, writeByte()
etc. and their read counterparts are directly available from the class RandomAccessFile
so using it alone is enough.