Reputation: 3253
I cannot understand what is the difference between
RandomAccessFile raf = new RandomAccessFile(file, "rw");
int offset = getOffset();
byte[] dataInBytes = getData();
raf.seek(offset);
raf.write(dataInBytes, 0, getSize())'
and
...
byte[] dataInBytes = getData();
raf.write(dataInBytes, offset, getSize());
I thought seeking and then writing is equivalent to using write function with offset instead of zero. But seems it is not the case. I do not know what's the difference yet, I just need to pass unit tests, and second version passes unit tests and the first does not.
What is the difference between those two approaches?
Upvotes: 0
Views: 196
Reputation: 21435
Look at the JavaDoc of RandomAccessFile#write(byte[]. int, int):
Writes len bytes from the specified byte array starting at offset off to this file.
Parameters:
b
- the data.
off
- the start offset in the data.
len
- the number of bytes to write.
The offset parameter that you pass into write(byte[], int, int)
is not an offset into the file, but an offset into the byte array that you pass.
Your first code snippet positions the RandomAccessFile
at position offset
and then writes getSize()
bytes from the beginning of the data array at that position.
Your second code snippets does not change the position within the RandomAccessFile
(that probably means starting to write at the beginning of the file) and then writes getSize()
bytes of the data array, beginning with the byte at position offset
in the byte array.
Upvotes: 3
Reputation: 147154
In the former the offset is into the file you are accessing. In the later it is an offset into the array.
Upvotes: 1